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
scripts/replatform.js
#!/usr/bin/env node
'use strict';
// commander ships inside the skill (vendor/); an incomplete install or an old Node says so
// instead of a stack trace.
function requireCommander() {
try {
return require('../vendor/commander');
} catch (error) {
if (error && (error.code === 'MODULE_NOT_FOUND' || error.code === 'ERR_REQUIRE_ESM')) {
process.stderr.write(`replatform: cannot load the bundled commander (${error.code}). ${require('../lib/toolkit-dependencies.js').FIX}\n`);
process.exit(1);
}
throw error;
}
}
const fs = require('node:fs/promises');
const fssync = require('node:fs');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { Command, Option } = requireCommander();
const {
RunController, readActive, findRun, requestCancellation, defaultEventsPath, readJson, exitCode,
} = require('../lib/run-controller.js');
const { loadArtifacts } = require('../lib/orchestration-state.js');
const { determineNextStep } = require('../lib/orchestration-router.js');
const { listUserActions, readUserAction, answerUserAction } = require('../lib/user-actions.js');
const { writeJsonAtomic } = require('../lib/orchestration-state.js');
const { chooseAdapter } = require('../lib/agent-adapters/index.js');
const { defaultProbeWixCli } = require('../lib/orchestration-preflight.js');
const { readTaskState } = require('../lib/task-state.js');
const { applyUserActionEffect } = require('../lib/user-action-effects.js');
const VERSION = '0.1.0';
function duration(value, { allowOff = false, min = 0, max = Infinity } = {}) {
if (allowOff && (value === undefined || value === 'off')) return null;
if (!/^\d+(ms|s|m|h|d)$/.test(String(value))) throw new Error(`invalid duration: ${value}`);
const [, amount, unit] = String(value).match(/^(\d+)(ms|s|m|h|d)$/);
const multiplier = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 }[unit];
const result = Number(amount) * multiplier;
if (result < min || result > max) throw new Error(`duration out of allowed range: ${value}`);
return result;
}
function positive(value, name, fallback) {
if (value === undefined) return fallback;
if (!/^\d+$/.test(String(value)) || Number(value) < 1) throw new Error(`${name} must be a positive integer`);
return Number(value);
}
function output(value, format = 'text', text = null) {
if (format === 'json') process.stdout.write(`${JSON.stringify(value)}\n`);
else if (format === 'jsonl') process.stdout.write(`${JSON.stringify(value)}\n`);
else process.stdout.write(`${text || JSON.stringify(value, null, 2)}\n`);
}
function rootDir() { return path.resolve(process.env.REPLATFORM_MIGRATIONS_DIR || path.join(process.cwd(), 'migrations')); }
async function resolveProject(value) {
if (!value) throw new Error('project is required (or set --project)');
if (/^rpr_[0-9a-f-]+$/.test(value)) {
const record = await findRun(rootDir(), value);
if (!record) throw new Error(`run ID not found: ${value}`);
return { projectDir: record.projectDir, runId: value };
}
const candidate = path.resolve(value);
// A value with path syntax is a path even before `run` creates its project directory.
// Only a bare name is resolved beneath the configured migrations root.
if (path.isAbsolute(value) || value.includes(path.sep) || value.startsWith('.')) return { projectDir: candidate, runId: null };
if (fssync.existsSync(candidate)) return { projectDir: candidate, runId: null };
return { projectDir: path.join(rootDir(), value), runId: null };
}
function projectArg(args, index = 1) { return args.project || args._[index]; }
function runtimeOptions(args) {
const format = args.format === 'event-stream' ? 'jsonl' : (args.format || 'jsonl');
if (!['text', 'json', 'jsonl'].includes(format)) throw new Error('format must be text, json, jsonl, or event-stream');
const statusIntervalMs = args.statusInterval === 'off' || (args.detach && args.statusInterval === undefined)
? null : duration(args.statusInterval || '60s', { min: 10000, max: 300000 });
if (!['auto', 'codex', 'claude'].includes(args.agent || 'auto')) throw new Error('agent must be auto, codex, or claude');
if (args.sourceUrl !== undefined) {
let source;
try { source = new URL(args.sourceUrl); } catch { throw new Error('source-url must be an https URL'); }
if (source.protocol !== 'https:' || source.username || source.password) throw new Error('source-url must be a credential-free https URL');
}
if (args.sourceMode !== undefined && !['public_content', 'authenticated_api', 'private_data', 'files_only'].includes(args.sourceMode)) throw new Error('invalid source-mode');
if (args.deliveryMode !== undefined && !['management', 'website', 'management_and_website'].includes(args.deliveryMode)) throw new Error('invalid delivery-mode');
if (args.managementImportMode !== undefined && !['standard', 'quick'].includes(args.managementImportMode)) throw new Error('invalid management-import-mode');
if (args.destination !== undefined && !(args.destination === 'new' || /^existing:[A-Za-z0-9_-]+$/.test(args.destination))) throw new Error('destination must be new or existing:<site-id>');
// An explicit new-site type, and Harmony's optional business type.
if (args.siteType !== undefined && !['headless', 'studio', 'harmony'].includes(args.siteType)) throw new Error('site-type must be headless, studio, or harmony');
if (args.siteBusinessType !== undefined && !['store', 'bookings', 'other'].includes(args.siteBusinessType)) throw new Error('site-business-type must be store, bookings, or other');
if (args.siteBusinessType !== undefined && args.siteType !== 'harmony') throw new Error('site-business-type is valid only with --site-type harmony');
if (args.siteType !== undefined && args.destination !== undefined && args.destination !== 'new') throw new Error('site-type applies only to --destination new');
// The existing-site mute answer, given up front (a new site is always muted).
if (args.notificationMute !== undefined && !['on', 'off'].includes(args.notificationMute)) throw new Error('notification-mute must be on or off');
if (args.notificationMute !== undefined && !/^existing:/.test(args.destination || '')) throw new Error('notification-mute applies only to --destination existing:<site-id>; a new site is always muted');
return {
agent: args.agent || 'auto', agentPath: args.agentPath, sourceUrl: args.sourceUrl, sourceMode: args.sourceMode,
deliveryMode: args.deliveryMode, destination: args.destination, managementImportMode: args.managementImportMode,
siteType: args.siteType, siteBusinessType: args.siteBusinessType, notificationMute: args.notificationMute,
fileInputPaths: args.file?.length ? args.file.map((filePath) => path.resolve(filePath)) : undefined,
oneClick: args.oneClick, dryRun: args.dryRun, eventsFile: args.eventsFile ? path.resolve(args.eventsFile) : null, vendorEvents: args.vendorEvents ? path.resolve(args.vendorEvents) : null,
statusIntervalMs, wallTimeoutMs: duration(args.wallTimeout || 'off', { allowOff: true, min: 60000, max: 7 * 86400000 }),
idleTimeoutMs: duration(args.idleTimeout || '15m', { min: 60000, max: 2 * 3600000 }),
maxAgentTurns: positive(args.maxAgentTurns, 'max-agent-turns', 12),
maxNoProgressContinuations: positive(args.maxNoProgressContinuations, 'max-no-progress-continuations', 1),
format,
};
}
function applyApproval(projectDir, request, answer) {
return applyUserActionEffect(projectDir, request, answer);
}
async function runCommand(args, { resume = false, resumeBlocked = resume, internalRunId = null } = {}) {
const target = await resolveProject(projectArg(args));
const options = runtimeOptions(args);
if (resume && [args.sourceUrl, args.sourceMode, args.file, args.deliveryMode, args.destination, args.managementImportMode, args.siteType, args.siteBusinessType, args.notificationMute, args.oneClick].some((value) => value !== undefined)) throw new Error('resume does not accept intake mutation options');
const controller = new RunController(target.projectDir, { ...options, resume, resumeBlocked, runId: internalRunId || undefined, onEvent: (event) => {
if (options.format === 'jsonl') process.stdout.write(`${JSON.stringify(event)}\n`);
} });
if (args.detach && !internalRunId) {
// The child receives a serialized, already parsed invocation; no shell or prompt is built.
const encoded = Buffer.from(JSON.stringify({ project: target.projectDir, options: { ...options, resume, resumeBlocked, runId: controller.id } })).toString('base64url');
const child = spawn(process.execPath, [__filename, '__supervise', encoded], { detached: true, stdio: 'ignore' });
child.unref();
const result = { schemaVersion: 1, runId: controller.id, project: path.basename(target.projectDir), outcome: 'running', nextAction: `replatform status ${controller.id}` };
// Allocate a lookup record before returning; the supervisor will replace it immediately.
await fs.mkdir(path.join(target.projectDir, 'state', 'runner', 'runs'), { recursive: true });
await writeJsonAtomic(path.join(target.projectDir, 'state', 'runner', 'runs', `${controller.id}.json`), { schemaVersion: 1, runId: controller.id, projectDir: target.projectDir, pid: child.pid, status: 'starting', updatedAt: new Date().toISOString() });
output(result, options.format, `Started detached run ${controller.id}.\nStatus: replatform status ${controller.id}`);
return 0;
}
const result = await controller.run();
if (options.format === 'json') output(result, 'json');
else if (options.format === 'text') output(result, 'text', `${result.outcome}: ${result.router?.reason || 'run finished'}${result.requestId ? `\nRequest: ${result.requestId}\nAnswer: ${result.nextAction}` : result.router?.reason === 'run_blocked' ? `\nRecorded blocker: ${JSON.stringify(result.router.resumeFrom)}\nNext: ${result.nextAction}` : ''}`);
return exitCode(result);
}
async function statusCommand(args) {
const target = await resolveProject(projectArg(args));
const active = await readActive(target.projectDir);
const artifacts = await loadArtifacts(target.projectDir);
const router = artifacts.run ? await determineNextStep(target.projectDir, artifacts) : null;
const historyDir = path.join(target.projectDir, 'state', 'runner', 'runs');
let latestRun = target.runId ? await findRun(rootDir(), target.runId) : null;
if (!latestRun) {
try {
const records = await Promise.all((await fs.readdir(historyDir)).filter((name) => name.endsWith('.json')).map((name) => readJson(path.join(historyDir, name))));
latestRun = records.filter(Boolean).sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')))[0] || null;
} catch (error) { if (error.code !== 'ENOENT') throw error; }
}
const eventPath = active?.eventPath || latestRun?.eventPath || defaultEventsPath(target.projectDir);
let lastEvent = null;
try { const lines = (await fs.readFile(eventPath, 'utf8')).trim().split('\n').filter(Boolean); if (lines.length) lastEvent = JSON.parse(lines.at(-1)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
const result = { schemaVersion: 1, project: path.basename(target.projectDir), activeRun: active ? { runId: active.runId, pid: active.pid, childPid: active.childPid, status: active.status } : null, orchestration: artifacts.run ? { status: artifacts.run.status, state: artifacts.run.currentState } : null, router, eventStream: { path: eventPath, lastEventId: lastEvent?.eventId || null, lastEventAt: lastEvent?.timestamp || null }, latestResult: latestRun?.result || null };
output(result, args.format || 'text', active ? `Run ${active.runId}: ${active.status}` : `No active run. ${router?.reason || 'No orchestration state.'}`);
return 0;
}
async function tailCommand(args) {
const target = await resolveProject(projectArg(args));
const active = await readActive(target.projectDir);
const eventFile = active?.eventPath || defaultEventsPath(target.projectDir);
const since = args.since;
let passedCursor = !since || !/^evt_[0-9a-f-]+$/.test(since);
const shouldPrint = (item) => {
if (!since) return true;
if (/^evt_[0-9a-f-]+$/.test(since)) {
if (!passedCursor && item.eventId === since) { passedCursor = true; return false; }
return passedCursor;
}
return Date.parse(item.timestamp) >= Date.now() - duration(since, { min: 0, max: 365 * 86400000 });
};
const print = async () => {
let text; try { text = await fs.readFile(eventFile, 'utf8'); } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
const lines = text.trim().split('\n').filter(Boolean);
for (const line of lines) {
const item = JSON.parse(line); if (!shouldPrint(item)) continue;
if ((args.format || 'jsonl') === 'text') process.stdout.write(`${item.timestamp} ${item.type}: ${item.message}\n`);
else process.stdout.write(`${line}\n`);
}
return lines.length;
};
let known = await print();
if (!args.follow) return 0;
while (true) {
await new Promise((resolve) => setTimeout(resolve, 1000));
let text = ''; try { text = await fs.readFile(eventFile, 'utf8'); } catch { continue; }
const lines = text.trim().split('\n').filter(Boolean);
for (const line of lines.slice(known)) {
const item = JSON.parse(line); if (shouldPrint(item)) process.stdout.write(`${line}\n`);
}
known = lines.length;
const current = await readActive(target.projectDir); if (!current) break;
}
return 0;
}
function allowedArtifact(requests, target) {
const normalized = target.replaceAll('\\', '/');
if (normalized.includes('..') || normalized.startsWith('/') || /^(config|state|source|raw)(\/|$)/.test(normalized)) return false;
return normalized.includes('/review/') || requests.some((request) => request.artifactRefs.some((ref) => ref.path === normalized));
}
async function showCommand(args) {
const target = await resolveProject(projectArg(args));
const id = args._[2]; if (!id) throw new Error('show requires request-id-or-artifact');
if (/^uar_[0-9a-f-]+$/.test(id)) { const request = await readUserAction(target.projectDir, id); output(request, args.format || 'text'); return 0; }
const requests = await listUserActions(target.projectDir, {});
if (!allowedArtifact(requests.map((row) => ({ ...row, artifactRefs: [] })), id)) {
// Index rows intentionally omit refs; read each action before authorizing an artifact.
const full = []; for (const row of requests) full.push(await readUserAction(target.projectDir, row.requestId));
if (!allowedArtifact(full, id)) throw new Error('artifact is not user-reviewable');
}
const fullPath = path.resolve(target.projectDir, id);
const root = `${path.resolve(target.projectDir)}${path.sep}`;
if (!fullPath.startsWith(root)) throw new Error('artifact escapes project');
const content = await fs.readFile(fullPath);
const max = positive(args.maxBytes, 'max-bytes', 1048576);
const cursor = args.cursor === undefined ? 0 : Number(args.cursor);
if (!Number.isInteger(cursor) || cursor < 0 || cursor > content.length) throw new Error('cursor must be a valid byte offset');
const emitted = content.subarray(cursor, cursor + max); const truncated = cursor + emitted.length < content.length;
const fullRequests = []; for (const row of requests) fullRequests.push(await readUserAction(target.projectDir, row.requestId));
const mediaType = fullRequests.flatMap((request) => request.artifactRefs).find((ref) => ref.path === id.replaceAll('\\', '/'))?.mediaType || 'text/plain';
const result = { schemaVersion: 1, path: id.replaceAll('\\', '/'), mediaType, totalBytes: content.length, cursor, emittedBytes: emitted.length, truncated, nextCursor: truncated ? cursor + emitted.length : null, content: emitted.toString('utf8') };
output(result, args.format || 'text', `${result.content}${truncated ? `\nTRUNCATED: showed ${emitted.length}B of ${content.length}B; rerun with --max-bytes ${content.length} or larger.` : ''}`);
return 0;
}
async function requestsCommand(args) {
const target = await resolveProject(projectArg(args));
const rows = await listUserActions(target.projectDir, { status: args.status || 'pending' });
const actions = await Promise.all(rows.map((row) => readUserAction(target.projectDir, row.requestId)));
const text = actions.map((action) => {
const answer = action.response.mode === 'choice'
? `--choice <${action.choices.map((choice) => choice.id).join('|')}>`
: action.response.mode === 'text' ? '--text "<answer>"' : '--acknowledge';
const choices = action.response.mode === 'choice'
? `\n Choices: ${action.choices.map((choice) => `${choice.id} (${choice.label})`).join(', ')}` : '';
const next = action.response.mode === 'none'
? `After completing it: replatform answer --project ${target.projectDir} --request-id ${action.requestId} --acknowledge --continue`
: `Answer: replatform answer --project ${target.projectDir} --request-id ${action.requestId} ${answer}`;
const prompt = action.response.mode === 'none' ? `\n Required action: ${action.prompt}` : '';
return `${action.requestId}: ${action.title} (${action.status})\n Response: ${action.response.mode}${choices}${prompt}\n Show: replatform show --project ${target.projectDir} ${action.requestId}\n Next: ${next}`;
}).join('\n\n') || 'No matching user actions.';
output(actions, args.format || 'text', text);
return 0;
}
async function tasksCommand(args) {
const target = await resolveProject(projectArg(args));
const state = await readTaskState(target.projectDir);
const active = await readActive(target.projectDir);
const result = state || { schemaVersion: 1, runId: active?.runId || target.runId || null, updatedAt: null, tasks: [], agents: [] };
output(result, args.format || 'text', result.tasks.length
? result.tasks.map((task) => `${task.state}: ${task.title}`).join('\n')
: 'No durable work state has been recorded for this run.');
return 0;
}
async function answerCommand(args) {
const target = await resolveProject(projectArg(args)); const requestId = args._[2];
if (!requestId) throw new Error('answer requires request id');
const variants = [args.choice !== undefined, args.text !== undefined, args.textFile !== undefined, args.acknowledge === true].filter(Boolean).length;
if (variants !== 1) throw new Error('answer requires exactly one of --choice, --text, --text-file, --acknowledge');
if (args.note !== undefined && args.choice === undefined && !args.acknowledge) throw new Error('note is supported only with a choice or acknowledgement');
const answer = args.acknowledge ? { acknowledged: true, ...(args.note !== undefined ? { note: args.note } : {}) } : args.choice !== undefined ? { choice: args.choice, ...(args.note !== undefined ? { note: args.note } : {}) } : { text: args.textFile ? await fs.readFile(path.resolve(args.textFile), 'utf8') : args.text };
const result = await answerUserAction(target.projectDir, requestId, answer, { applyEffect: (request, normalized) => applyApproval(target.projectDir, request, normalized) });
if (!args.continue) { output(result, args.format || 'text', `Answered ${requestId}. Resume: replatform resume ${target.projectDir}`); return 0; }
args._ = ['run', target.projectDir]; args.project = target.projectDir; return runCommand(args, { resume: true, resumeBlocked: false });
}
async function doctorCommand(args) {
const value = projectArg(args); const target = value ? await resolveProject(value) : null;
const ids = args.agent && args.agent !== 'auto' ? [args.agent] : ['codex', 'claude'];
const adapters = ids.map((id) => chooseAdapter(id, { agentPath: args.agentPath }));
const active = target ? await readActive(target.projectDir) : null;
const result = { schemaVersion: 1, node: process.version, project: target?.projectDir || null, writable: target ? await fs.access(target.projectDir, fssync.constants.W_OK).then(() => true).catch(() => false) : null, adapters, activeRun: active };
output(result, args.format || 'text', adapters.map((a) => `${a.id || args.agent}: ${a.ok ? 'available' : a.reason}`).join('\n'));
return adapters.some((item) => item.ok) ? 0 : 2;
}
async function projectsCommand(args) {
const root = rootDir();
let entries;
try { entries = await fs.readdir(root, { withFileTypes: true }); } catch (error) {
if (error.code === 'ENOENT') { output({ schemaVersion: 1, projects: [] }, args.format || 'text', 'No migration projects.'); return 0; }
throw error;
}
const projects = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
const projectDir = path.join(root, entry.name); const artifacts = await loadArtifacts(projectDir);
if (!artifacts.run && !fssync.existsSync(path.join(projectDir, 'state', 'runner'))) continue;
const active = await readActive(projectDir);
const router = artifacts.run ? await determineNextStep(projectDir, artifacts) : null;
projects.push({ project: entry.name, activeRun: active ? { runId: active.runId, status: active.status } : null, orchestration: artifacts.run ? { status: artifacts.run.status, state: artifacts.run.currentState } : null, router: router ? { state: router.nextState, reason: router.reason } : null });
}
projects.sort((a, b) => a.project.localeCompare(b.project));
output({ schemaVersion: 1, projects }, args.format || 'text', projects.map((item) => item.project).join('\n') || 'No migration projects.');
return 0;
}
async function accountCommand(args) {
const wixCli = await defaultProbeWixCli();
const result = {
schemaVersion: 1,
available: wixCli.available,
authState: wixCli.authState,
...(wixCli.identity || wixCli.email ? { identity: wixCli.identity || wixCli.email } : {}),
...(wixCli.reason ? { reason: wixCli.reason } : {}),
};
const confirmed = result.authState === 'authenticated' && Boolean(result.identity);
output(result, args.format || 'text', confirmed
? `Authenticated Wix CLI identity: ${result.identity}`
: `Wix CLI identity could not be confirmed: ${result.reason || 'unknown'}`);
return confirmed ? 0 : 2;
}
function commandArgs(command, positional, options) {
return { ...options, _: [command, ...(positional === undefined ? [] : [positional])] };
}
function addRuntimeOptions(command, { intake = false } = {}) {
command
.addHelpText('after', '\nThis command is non-interactive: it never prompts, opens a pager/editor/browser/login, or waits for stdin.\n')
.addOption(new Option('--agent <id>', 'auto selects a compatible adapter (Codex first); codex and claude require that exact adapter.').choices(['auto', 'codex', 'claude']).default('auto'))
.option('--agent-path <path>', 'adapter executable override (testing/development)')
.addOption(new Option('--format <format>', 'jsonl streams lifecycle events (default); json emits one final result; text is human-readable; event-stream aliases jsonl.').choices(['text', 'json', 'jsonl', 'event-stream']).default('jsonl'))
.option('--status-interval <duration>', 'liveness heartbeat interval: 60s foreground by default, off detached; use off to disable')
.option('--events-file <path>', 'write normalized JSONL events to this file')
.option('--vendor-events <path>', 'write raw vendor events to this diagnostic file')
.option('--wall-timeout <duration>', 'whole-run deadline; use off to disable')
.option('--idle-timeout <duration>', 'maximum time without observed progress')
.option('--max-agent-turns <count>', 'maximum agent turns in this supervisor run')
.option('--max-no-progress-continuations <count>', 'maximum same-route retries')
.option('--detach', 'start the supervisor in the background')
.option('--no-resume-agent-session', 'do not reuse an adapter session when supported');
if (intake) {
command
.option('--source-url <https-url>', 'source URL; credentials are rejected')
.addOption(new Option('--source-mode <mode>', 'public_content reads public pages; authenticated_api uses normal source API access; private_data needs protected credentials; files_only imports supplied files.').choices(['public_content', 'authenticated_api', 'private_data', 'files_only']))
.option('--file <path>', 'input file for files_only mode; repeat for each source file', (value, previous) => [...(previous || []), value])
.addOption(new Option('--delivery-mode <mode>', 'management migrates backend data; website migrates the frontend only; management_and_website performs both.').choices(['management', 'website', 'management_and_website']))
.option('--destination <strategy>', 'new creates a site; existing:<site-id> adopts the named existing site')
.addOption(new Option('--site-type <type>', 'type of a new destination site: headless (website in code), studio or harmony (website designed in a Wix editor). Required before a new site is created; never defaulted.').choices(['headless', 'studio', 'harmony']))
.addOption(new Option('--site-business-type <type>', 'with --site-type harmony only: store, bookings or other records the business context for the run. It does not change how the site is created: Harmony always starts from the blank template.').choices(['store', 'bookings', 'other']))
.addOption(new Option('--notification-mute <answer>', 'with --destination existing:<site-id> only: on mutes all site notifications (including customer emails) until someone unmutes; off leaves them on, so customers and the owner may get emails for imported records. Asked before the first write when not given; never defaulted.').choices(['on', 'off']))
.addOption(new Option('--management-import-mode <mode>', 'standard uses the full discovery/mapping flow; quick uses a public adapter and bounded plan.').choices(['standard', 'quick']))
.option('--one-click', 'record an explicit user one-click decision')
.option('--dry-run', 'request the existing dry-run execution path');
}
return command;
}
async function cancelCommand(args) {
const target = await resolveProject(projectArg(args));
const gracePeriodMs = duration(args.gracePeriod || '60s', { min: 5000, max: 600000 });
const result = await requestCancellation(target.projectDir, { reason: args.reason || 'canceled by operator', gracePeriodMs });
if (args.wait !== false) {
const deadline = Date.now() + gracePeriodMs + 5000;
while (Date.now() < deadline && await readActive(target.projectDir)) await new Promise((resolve) => setTimeout(resolve, 250));
const record = await readJson(path.join(target.projectDir, 'state', 'runner', 'runs', `${result.active.runId}.json`));
if (record?.result) { output(record.result, args.format || 'text', `${record.result.outcome}: cancellation finished.`); return exitCode(record.result); }
}
output(result, args.format || 'text', `Cancellation requested for ${result.active.runId}.`);
return 0;
}
function setExit(handler) {
return async (...values) => { process.exitCode = await handler(...values); };
}
function createProgram() {
const program = new Command();
program
.name('replatform')
.description('Non-interactive supervisor for artifact-first RePlatform migrations.')
.version(VERSION, '--version', 'print the CLI version')
.showHelpAfterError('(all commands are non-interactive; they never prompt, open a pager, or wait for stdin)')
.addHelpText('after', '\nPurpose: the CLI supervises an agent using wix-replatform; it does not replace the skill or migration receipts.\nFull guide: CLI.md alongside this installed wix-replatform bundle.\nExit codes: 0 completed, 1 failed, 2 invalid input, 3 waiting for user, 4 blocked, 5 canceled/interrupted, 6 timeout.\n');
addRuntimeOptions(program.command('run [project]').description('Start a non-interactive foreground supervised migration run.').option('--project <path>', 'project directory'), { intake: true })
.action(setExit((project, options) => runCommand(commandArgs('run', project, options))));
addRuntimeOptions(program.command('resume [project]').description('Resume an unfinalized migration project non-interactively.').option('--project <path>', 'project directory'), { intake: false })
.action(setExit((project, options) => runCommand(commandArgs('resume', project, options), { resume: true })));
program.command('status [project-or-run-id]').description('Read durable orchestration and runner state.').option('--project <path>', 'project directory').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((project, options) => statusCommand(commandArgs('status', project, options))));
program.command('tail [project-or-run-id]').description('Render normalized runner events without a pager.').option('--project <path>', 'project directory').option('--follow', 'wait for events until the run terminates').option('--since <event-id-or-duration>', 'exclusive event cursor or inclusive duration window').addOption(new Option('--format <format>', 'stdout format').choices(['jsonl', 'text']).default('jsonl'))
.action(setExit((project, options) => tailCommand(commandArgs('tail', project, options))));
program.command('cancel <project-or-run-id>').description('Request supervised cancellation of a live run.').option('--project <path>', 'project directory').option('--grace-period <duration>', 'grace period before forced termination', '60s').option('--no-wait', 'return after durable acknowledgement').option('--reason <text>', 'operator-visible reason', 'canceled by operator').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((project, options) => cancelCommand(commandArgs('cancel', project, options))));
program.command('doctor [project-or-run-id]').description('Check local agent and project-run capability without exposing credentials.').option('--project <path>', 'project directory').addOption(new Option('--agent <id>', 'agent adapter').choices(['auto', 'codex', 'claude']).default('auto')).option('--agent-path <path>', 'adapter executable override').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((project, options) => doctorCommand(commandArgs('doctor', project, options))));
program.command('requests [project-or-run-id]').description('List durable human actions.').option('--project <path>', 'project directory').addOption(new Option('--status <status>', 'request status').choices(['pending', 'answered', 'canceled']).default('pending')).option('--since <duration>', 'only actions since this duration').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((project, options) => requestsCommand(commandArgs('requests', project, options))));
program.command('tasks [project-or-run-id]').description('Read persisted operator-facing work state.').option('--project <path>', 'project directory').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((project, options) => tasksCommand(commandArgs('tasks', project, options))));
program.command('show [project-or-run-id] [request-id-or-artifact]').description('Print a durable action or authorized review artifact. With --project, supply the item positionally.').option('--project <path>', 'project directory').option('--max-bytes <count>', 'maximum emitted bytes', '1048576').option('--cursor <byte-offset>', 'artifact byte offset', '0').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((first, second, options) => {
const item = second || (options.project ? first : null);
const project = options.project || (second ? first : null);
if (!item) throw new Error('show requires request-id-or-artifact');
return showCommand({ ...options, project, _: ['show', project, item] });
}));
addRuntimeOptions(program.command('answer [project-or-run-id] [request-id]').description('Record one immutable human response. With --project, supply the request ID positionally or through --request-id.').option('--project <path>', 'project directory').option('--request-id <id>', 'durable user-action request ID').option('--choice <choice-id>', 'declared choice ID').option('--note <text>', 'optional reviewer or acknowledgement note').option('--text <text>', 'free-text answer').option('--text-file <path>', 'UTF-8 answer file').option('--acknowledge', 'state that a required manual action was completed; the resumed stage must verify it').option('--continue', 'continue in the foreground after answering; preserve explicit run holds'), { intake: false })
.action(setExit((first, second, options) => {
const requestId = options.requestId || second || (options.project ? first : null);
const project = options.project || (second ? first : null);
if (!requestId) throw new Error('answer requires request-id (positional or --request-id)');
return answerCommand({ ...options, project, _: ['answer', project, requestId] });
}));
program.command('projects').description('List migration projects beneath the configured migrations root.').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((options) => projectsCommand(options)));
program.command('account').description('Report the identity currently authenticated in the local Wix CLI.').addOption(new Option('--format <format>', 'stdout format').choices(['text', 'json']).default('text'))
.action(setExit((options) => accountCommand(options)));
program.command('completion <shell>').description('Print static completion for bash, zsh, or fish.')
.action((shell) => {
if (!['bash', 'zsh', 'fish'].includes(shell)) throw new Error('completion requires bash, zsh, or fish');
const commands = 'run resume status tail cancel doctor requests tasks show answer projects account help completion';
if (shell === 'bash') process.stdout.write(`_replatform() { COMPREPLY=( $(compgen -W '${commands}' -- "${'${COMP_WORDS[1]}'}") ); }\ncomplete -F _replatform replatform\n`);
if (shell === 'zsh') process.stdout.write(`#compdef replatform\n_arguments '1:command:(${commands})' '*::arg:->args'\n`);
if (shell === 'fish') process.stdout.write(`${commands.split(' ').map((item) => `complete -c replatform -f -a ${item}`).join('\n')}\n`);
});
program.command('__supervise <payload>', { hidden: true }).action(setExit(async (payload) => {
const data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
const controller = new RunController(data.project, { ...data.options, onEvent: () => {} });
return exitCode(await controller.run());
}));
return program;
}
async function main(argv = process.argv.slice(2)) {
const program = createProgram();
// Commander remains the single formatter. JSON wraps its generated help for callers
// that need discovery without parsing terminal columns.
if (argv[0] === 'help' && argv.includes('--format')) {
const format = argv[argv.indexOf('--format') + 1];
if (!['text', 'json'].includes(format)) throw new Error('help format must be text or json');
const requested = argv.slice(1).find((item) => !item.startsWith('-'));
const target = requested ? program.commands.find((command) => command.name() === requested) : program;
if (requested && !target) throw new Error(`unknown command: ${requested}`);
const helpText = target.helpInformation();
output({ schemaVersion: 1, command: requested || null, help: helpText }, format, helpText);
return 0;
}
await program.parseAsync(['node', 'replatform', ...argv]);
return process.exitCode || 0;
}
if (require.main === module) main().catch((error) => { process.stderr.write(`${error.message}\n`); process.exitCode = 2; });
module.exports = { main, createProgram, duration, runtimeOptions, resolveProject, allowedArtifact, accountCommand, tasksCommand };
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