Generated banner for Wix Replatform
Generated logo for Wix Replatform

Wix Replatform

WixOfficialPublished by Wix

  • Skill
  • Workflow
  • Automation and integrations
  • MIT
  • Low risk
  • Has scripts

From the author

Routes RePlatform source-to-Wix migrations to the next required workflow module by inspecting authoritative migration artifacts. Use when starting, resuming, or recovering a migration run.
— the description by Wix

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/wix/wix-replatform-fya3/download
  2. Unzip 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>/ (or REPLATFORM_MIGRATIONS_DIR) before inspecting or creating anything. Only that project's artifacts are authoritative.

  • Preserve EXPECTATIONS.md at 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 review

Delivery 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:

  1. Resolve the project and initialize/load its orchestration artifacts.

  2. Run node skills/wix-replatform/scripts/orchestration-route.js <projectDir>.

  3. Dispatch the nextResource to 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 read state/attempts/write-attempts.ndjson raw; use scripts/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.

  4. 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.

  5. 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.md and mapping-gaps.json, or execution/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 — see rp-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.

  6. 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_rejected is blocked before any setup or import write, and mapping_approval_rejected returns to rp-mapper for 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) is blocked with errors and the producer as nextResource. 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) carry importProgress. interrupted lists recoveryArtifacts: resume it, never a second import. interruptedReport: "missing": first run scripts/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 situationDispatch
project, delivery mode, source mode, or grouped intake is unresolvedresources/rp-project-intake/
destination is absent, conflicting, or needs creation/adoptionresources/rp-destination/
source URL/files/config/acquisition mode/credentials are required, including source credentials said to exist already on another siteresources/rp-source-inputs/
deterministic preflight is missing, repaired, or blocked on CLI checksresources/rp-preflight/
quick mode needs platform resolution, endpoint preflight, plan, extraction, or importselected resources/rp-quick-<platform>/
source schema is missingresources/rp-discovery/ and its selected source adapter
mapping is missing or needs reviewresources/rp-mapper/
Wix requirements are missingresources/rp-setup-discovery/
import code/review is missing or staleresources/rp-import-codegen/
setup verification is missingresources/rp-execute-setup/
backend completion report is missingresources/rp-execute-import/
frontend-only work, or integrated website handoff/build/gap loop/release receipt is incompleteresources/rp-website-continuation/
aggregate completion is missingresources/rp-execution-policy/
aggregate completion exists but the local review publication or current recap is missingresources/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_website mode 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 completed with completion/migration-completion.json, or blocked with 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.

  • website means frontend only; management_and_website means 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 by rp-destination's coordinator and is never published, unpublished or handed to wix-headless-replatform; its website and publication remain operator handoff items.

  • Do not implement a storefront manually when wix-headless-replatform is 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

lib/run-controller.js

'use strict';

// The runner deliberately owns only process supervision and presentation. Routing, receipts,
// and migration mutations remain owned by the existing skill artifacts.
const fs = require('node:fs/promises');
const path = require('node:path');
const crypto = require('node:crypto');
const { loadArtifacts, initArtifacts, writeJsonAtomic, updateDecisionObject, transitionRun } = require('./orchestration-state.js');
const { determineNextStep } = require('./orchestration-router.js');
const { validateMigrationCompletion, loadMigrationCompletionInputs } = require('./migration-completion.js');
const { pendingUserActionGate } = require('./user-actions.js');
const { applySiteTypePair, resolveSiteTypePair } = require('./destination-choice.js');
const { normalizeTargetSiteStrategy } = require('./orchestration-decisions.js');
const { readEnvFile, upsertEnvFile } = require('./config-env.js');
const { chooseAdapter, launch, requestCancel } = require('./agent-adapters/index.js');
const { readTaskState, writeTaskState, createTaskState, selectRoute, startRoute, waitForInput, startDirectAgent, finishDirectAgent, recordWorker, finishCurrent, reconcileTaskState } = require('./task-state.js');

const SCHEMA_VERSION = 1;
const RUNNER_DIR = ['state', 'runner'];

const iso = () => new Date().toISOString();
const runId = () => `rpr_${crypto.randomUUID()}`;
const runnerDir = (projectDir) => path.join(projectDir, ...RUNNER_DIR);
const activePath = (projectDir) => path.join(runnerDir(projectDir), 'active.json');
const historyPath = (projectDir, id) => path.join(runnerDir(projectDir), 'runs', `${id}.json`);
const defaultEventsPath = (projectDir) => path.join(runnerDir(projectDir), 'events.ndjson');
const cancelPath = (projectDir) => path.join(runnerDir(projectDir), 'cancel-request.json');

async function readJson(filePath) {
  try { return JSON.parse(await fs.readFile(filePath, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
}

async function ensureInitialArtifacts(projectDir) {
  const artifacts = await loadArtifacts(projectDir);
  if (artifacts.run) return artifacts;
  return initArtifacts(projectDir);
}

function safeRelative(projectDir, item) {
  const relative = path.relative(projectDir, item);
  return relative && !relative.startsWith('..') && !path.isAbsolute(relative) ? relative.replaceAll(path.sep, '/') : null;
}

async function appendLine(filePath, value) {
  await fs.mkdir(path.dirname(filePath), { recursive: true });
  await fs.appendFile(filePath, `${JSON.stringify(value)}\n`, 'utf8');
}

async function findRun(rootDir, id) {
  if (!/^rpr_[0-9a-f-]+$/.test(id)) return null;
  // Projects normally sit one level beneath the migrations root. A bounded recursive
  // lookup also keeps existing runs observable after a project was nested accidentally.
  const pending = [{ directory: rootDir, depth: 0 }];
  while (pending.length) {
    const { directory, depth } = pending.pop();
    const direct = await readJson(historyPath(directory, id));
    if (direct) return direct;
    if (depth >= 3) continue;
    let entries;
    try { entries = await fs.readdir(directory, { withFileTypes: true }); } catch { continue; }
    for (const entry of entries) {
      if (entry.isDirectory() && !['state', 'orchestration', 'completion', 'execution', 'website'].includes(entry.name)) {
        pending.push({ directory: path.join(directory, entry.name), depth: depth + 1 });
      }
    }
  }
  return null;
}

async function readActive(projectDir) { return readJson(activePath(projectDir)); }

async function applyInvocationInputs(projectDir, inputs) {
  const artifacts = await ensureInitialArtifacts(projectDir);
  const decisions = artifacts.decisions;
  // `--destination existing:<site-id>` is a strategy plus the site to adopt; only the strategy is a decision.
  const existingDestination = typeof inputs.destination === 'string' ? /^existing:(.+)$/.exec(inputs.destination) : null;
  const destinationStrategy = existingDestination ? 'existing' : inputs.destination;
  const mappings = {
    sourceUrl: inputs.sourceUrl,
    sourceMode: inputs.sourceMode,
    fileInputPaths: inputs.fileInputPaths,
    deliveryMode: inputs.deliveryMode,
    targetSiteStrategy: destinationStrategy === undefined ? undefined : normalizeTargetSiteStrategy(destinationStrategy),
    managementImportMode: inputs.managementImportMode,
    notificationMute: inputs.notificationMute,
    ...(inputs.oneClick ? { automationMode: 'one_click' } : {}),
    ...(inputs.dryRun ? { dryRun: true } : {}),
  };
  let changed = false;
  for (const [key, value] of Object.entries(mappings)) {
    if (value === undefined) continue;
    const existing = decisions[key] && decisions[key].value;
    if (existing !== undefined && JSON.stringify(existing) !== JSON.stringify(value)) {
      throw new Error(`CLI input conflicts with existing user decision: ${key}`);
    }
    if (existing === undefined) { updateDecisionObject(decisions, key, value, { source: 'user' }); changed = true; }
  }
  // The site-type pair lands in the same single decisions write. A Harmony
  // flag with no business type records `unknown` (source not_asked) and raises no request.
  if (inputs.siteType !== undefined) {
    const pair = resolveSiteTypePair({
      siteType: inputs.siteType,
      businessType: inputs.siteType === 'harmony' ? (inputs.siteBusinessType || 'unknown') : inputs.siteBusinessType,
      businessTypeSource: inputs.siteType === 'harmony' && !inputs.siteBusinessType ? 'not_asked' : 'user',
    });
    try {
      if (applySiteTypePair(decisions, pair, { rationale: 'replatform CLI --site-type' }).changed) changed = true;
    } catch (error) {
      throw new Error(`CLI input conflicts with existing user decision: targetSiteType (${error.message})`);
    }
  } else if (inputs.siteBusinessType !== undefined) {
    throw new Error('site-business-type is valid only with --site-type harmony');
  }
  if (existingDestination) {
    const wixEnvPath = path.join(projectDir, 'config', 'wix.env');
    let current = {};
    try { current = await readEnvFile(wixEnvPath); } catch (error) { if (!error || error.code !== 'ENOENT') throw error; }
    const recorded = String(current.WIX_SITE_ID || '').trim();
    if (recorded && recorded !== existingDestination[1]) throw new Error('CLI input conflicts with existing user decision: WIX_SITE_ID');
    await upsertEnvFile(wixEnvPath, { WIX_SITE_STRATEGY: 'existing', WIX_SITE_ID: existingDestination[1], ...(inputs.notificationMute ? { WIX_MUTE_NOTIFICATIONS: inputs.notificationMute } : {}) });
  }
  if (changed) await writeJsonAtomic(path.join(projectDir, 'orchestration', 'decisions.json'), decisions);
  return artifacts;
}

async function resumeStaleTelemetry(projectDir) {
  try {
    const { resumeIfStale } = require('../resources/rp-telemetry/lib/telemetry-recorder.js');
    return await resumeIfStale(projectDir, { trigger: 'supervisor' });
  } catch (error) {
    return { resumed: false, reason: 'error', trigger: 'supervisor', error: String((error && error.message) || error) };
  }
}

function bootstrap(projectDir) {
  // Only this already-validated absolute path is variable. Intake values stay in artifacts.
  return `Use the installed wix-replatform skill for the migration project at ${projectDir}. Read durable orchestration artifacts and the latest accepted CLI invocation, route, then perform only the selected stage. Do not claim completion from prose. When human input or review is required, create a durable user action and end this turn; never use an interactive question UI or wait for terminal input.`;
}

// A pending action is intentionally included in the normalized stream. A consumer must be
// able to render and answer a checkpoint from JSONL alone, without first reading a project file.
// Keep this to operator-facing fields; do not expose effects or a later answer here.
function userActionSummary(request) {
  return {
    requestId: request.requestId,
    kind: request.kind,
    stage: request.stage,
    title: request.title,
    prompt: request.prompt,
    response: request.response,
    choices: request.choices,
    artifactRefs: request.artifactRefs,
  };
}

function makeResult({ id, projectDir, outcome, adapter = null, route = null, completion = null, nextAction = null, request = null }) {
  return {
    schemaVersion: SCHEMA_VERSION,
    runId: id,
    project: path.basename(projectDir),
    outcome,
    agent: adapter ? { id: adapter.id, version: adapter.version || null, sessionId: null } : null,
    router: route ? { state: route.nextState, reason: route.reason, nextResource: route.nextResource || null,
      ...(route.reason === 'run_blocked' ? { resumeFrom: route.resumeFrom, resumeWith: route.resumeWith } : {}),
    } : null,
    completion: { validated: Boolean(completion && completion.ok), artifact: completion && completion.ok ? 'completion/migration-completion.json' : null },
    artifacts: request ? request.artifactRefs.map((ref) => ref.path) : route?.reason === 'run_blocked' ? ['orchestration/run.json'] : [],
    ...(request ? {
      requestId: request.requestId,
      kind: request.kind,
      choices: request.choices,
      userAction: userActionSummary(request),
    } : {}),
    ...(route?.blocker ? {blocker:route.blocker} : {}),
    nextAction,
  };
}

function exitCode(result) {
  return ({ completed: 0, waiting_for_user: 3, blocked: 4, canceled: 5, interrupted: 5, timed_out: 6 })[result.outcome] ?? 1;
}

class RunController {
  constructor(projectDir, options = {}) {
    this.projectDir = path.resolve(projectDir);
    this.options = { agent: 'auto', maxAgentTurns: 12, maxNoProgressContinuations: 1, gracePeriodMs: 60000, ...options };
    this.id = options.runId || runId();
    this.eventFiles = new Set([options.eventsFile || defaultEventsPath(this.projectDir)]);
    this.vendorEventsPath = options.vendorEvents || null;
    this.lastObservationAt = Date.now();
    this.child = null;
    this.adapter = null;
    this.taskState = null;
    this.closed = false;
  }

  async emit(type, state, message, extra = {}) {
    const event = { schemaVersion: SCHEMA_VERSION, eventId: `evt_${crypto.randomUUID()}`, timestamp: iso(), runId: this.id, type, state, message, ...extra };
    for (const filePath of this.eventFiles) await appendLine(filePath, event);
    this.options.onEvent?.(event);
    return event;
  }

  async writeRecord(patch = {}) {
    // `startedAt` and `telemetryResume` are carried on the controller and included in every
    // write, because the record is rebuilt from scratch each time. `startedAt` in active.json is
    // what an explicit telemetry `start` inside this run reads to join the session this run
    // opened (one supervisor process is one telemetry session).
    const record = { schemaVersion: SCHEMA_VERSION, runId: this.id, projectDir: this.projectDir, pid: process.pid, childPid: this.child?.pid || null, adapter: this.adapter ? { id: this.adapter.id, version: this.adapter.version || null } : null, eventPath: [...this.eventFiles][0], status: 'running', updatedAt: iso(), ...(this.startedAt ? { startedAt: this.startedAt } : {}), ...(this.telemetryResume ? { telemetryResume: this.telemetryResume } : {}), ...patch };
    await fs.mkdir(path.dirname(historyPath(this.projectDir, this.id)), { recursive: true });
    await writeJsonAtomic(historyPath(this.projectDir, this.id), record);
    if (!this.closed) await writeJsonAtomic(activePath(this.projectDir), record);
    return record;
  }

  async updateTasks(change) {
    if (!this.taskState) return null;
    change(this.taskState);
    this.taskState = await writeTaskState(this.projectDir, this.taskState);
    return this.taskState;
  }

  async recordInvocation() {
    const filePath = path.join(this.projectDir, 'orchestration', 'cli-invocations.ndjson');
    const safe = ['agent', 'sourceUrl', 'sourceMode', 'fileInputPaths', 'deliveryMode', 'destination', 'managementImportMode', 'siteType', 'siteBusinessType', 'notificationMute', 'oneClick', 'dryRun'].reduce((out, key) => {
      if (this.options[key] !== undefined) out[key] = this.options[key]; return out;
    }, {});
    await appendLine(filePath, { schemaVersion: SCHEMA_VERSION, runId: this.id, acceptedAt: iso(), options: safe });
  }

  async cancellationRequested() { return readJson(cancelPath(this.projectDir)); }

  async setOrchestrationCancellation(status) {
    const artifacts = await loadArtifacts(this.projectDir);
    if (!artifacts.run) return;
    const run = transitionRun(artifacts.run, { state: status, activePhase: 'orchestration', status, needsUserInput: false, needsLlm: false });
    await writeJsonAtomic(path.join(this.projectDir, 'orchestration', 'run.json'), run);
  }

  async finish(result) {
    if (this.closed) return result;
    this.closed = true;
    await this.updateTasks((state) => finishCurrent(state, result.outcome === 'waiting_for_user' ? 'waiting_for_input' : result.outcome === 'timed_out' ? 'interrupted' : result.outcome));
    await this.emit('result', result.outcome, 'Run result.', { result });
    await this.writeRecord({ status: result.outcome, result, endedAt: iso() });
    try { await fs.unlink(activePath(this.projectDir)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
    return result;
  }

  async waitForChild() {
    return new Promise((resolve) => this.child.once('close', (code, signal) => resolve({ code, signal })));
  }

  async run() {
    await fs.mkdir(this.projectDir, { recursive: true });
    const alreadyActive = await readActive(this.projectDir);
    if (alreadyActive && alreadyActive.runId !== this.id && alreadyActive.status === 'running') {
      throw new Error(`project already has an active run: ${alreadyActive.runId}`);
    }
    await applyInvocationInputs(this.projectDir, this.options);
    const existing = await loadArtifacts(this.projectDir);
    const resumeHold = this.options.resume && this.options.resumeBlocked !== false;
    if (this.options.resume && (existing.run?.status !== 'blocked' || resumeHold) && ['canceled', 'interrupted', 'cancel_requested', 'blocked'].includes(existing.run?.status)) {
      const resumed = transitionRun(existing.run, { state: 'initialized', activePhase: 'orchestration', status: 'running', needsUserInput: false, needsLlm: false });
      await writeJsonAtomic(path.join(this.projectDir, 'orchestration', 'run.json'), resumed);
      try { await fs.unlink(cancelPath(this.projectDir)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
    }
    // Once per supervisor process, before the first loop iteration: a supervisor start is a new
    // execution, so an open telemetry journal records a new session (or joins one opened in the
    // last minute). Never from the loop, the router or `status`. Fail-soft and silent: the
    // result lives only in this run's record, never in the event stream or on screen.
    this.startedAt = iso();
    this.telemetryResume = existing.run?.status === 'blocked' && !resumeHold
      ? { resumed: false, reason: 'run_blocked', trigger: 'supervisor' }
      : await resumeStaleTelemetry(this.projectDir);
    await this.recordInvocation();
    await this.writeRecord();
    const persistedTaskState = await readTaskState(this.projectDir);
    this.taskState = persistedTaskState?.runId === this.id ? await reconcileTaskState(this.projectDir, persistedTaskState) : createTaskState(this.id);
    await writeTaskState(this.projectDir, this.taskState);
    await this.emit('started', 'running', 'Supervisor started.', { evidence: { kind: 'process', ref: String(process.pid) } });
    const started = Date.now();
    this.startedAtMs = started;
    let turns = 0;
    let sameRoute = 0;
    let priorRoute = null;
    while (turns <= this.options.maxAgentTurns) {
      const cancellation = await this.cancellationRequested();
      if (cancellation) return this.cancel(cancellation);
      if (this.options.wallTimeoutMs && Date.now() - started > this.options.wallTimeoutMs) {
        return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'timed_out', nextAction: 'Resume with replatform resume <project> after investigating the timeout.' }));
      }
      const artifacts = await loadArtifacts(this.projectDir);
      // An explicit operator hold precedes pending requests and stale-request recovery.
      const actionGate = artifacts.run?.status === 'blocked' ? null : await pendingUserActionGate(this.projectDir);
      if (actionGate?.request) {
        const request = actionGate.request;
        await this.updateTasks((state) => waitForInput(state, request));
        const route = { nextState: 'awaiting_user_action', reason: 'pending_user_action', nextResource: null };
        await this.emit('user_action_requested', 'waiting_for_user', request.prompt, {
          requestId: request.requestId,
          title: request.title,
          userAction: userActionSummary(request),
          evidence: { kind: 'user_action', ref: `orchestration/user-actions/${request.requestId}.json` },
        });
        await this.emit('waiting_for_user', 'waiting_for_user', 'Waiting for a durable user action answer.', { requestId: request.requestId });
        const response = request.response.mode === 'choice'
          ? `--choice <${request.choices.map((choice) => choice.id).join('|')}>`
          : request.response.mode === 'text' ? '--text "<answer>"' : '--acknowledge';
        return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'waiting_for_user', route, request, nextAction: `replatform answer --project ${this.projectDir} --request-id ${request.requestId} ${response} --continue` }));
      }
      const route = await determineNextStep(this.projectDir, artifacts);
      await this.updateTasks((state) => selectRoute(state, route));
      await this.emit('routed', 'running', route.reason, { evidence: { kind: 'router', ref: route.nextResource || route.reason }, route });
      if (!route.ok) return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'failed', route, nextAction: 'Inspect orchestration artifacts and repair the reported validation error.' }));
      // The existing-site mute question is a durable request, not an agent turn: the next
      // pass finds it pending and waits for `replatform answer`.
      if (route.reason === 'missing_notification_mute_decision') {
        await require('./notification-mute.js').ensureNotificationMuteRequest(this.projectDir);
        continue;
      }
      if (route.nextState === 'completed') {
        const completionInputs = await loadMigrationCompletionInputs(this.projectDir);
        const completion = validateMigrationCompletion(completionInputs.completion, completionInputs);
        if (completion.ok) return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'completed', route, completion }));
      }
      if (['blocked', 'canceled', 'interrupted', 'cancel_requested'].includes(route.nextState)) {
        const outcome = route.nextState === 'cancel_requested' ? 'interrupted' : route.nextState;
        return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome, route, nextAction: route.reason === 'run_blocked' ? route.blocker.requiredInput : route.nextState === 'blocked' ? 'Inspect the route reason and satisfy the named prerequisite.' : 'Use replatform resume <project> when ready.' }));
      }
      const routeKey = `${route.nextState}:${route.reason}:${route.nextResource || ''}`;
      sameRoute = routeKey === priorRoute ? sameRoute + 1 : 0;
      priorRoute = routeKey;
      if (sameRoute > this.options.maxNoProgressContinuations) {
        return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'blocked', route, nextAction: 'The selected stage made no durable progress; inspect its artifacts before resuming.' }));
      }
      if (turns >= this.options.maxAgentTurns) return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'timed_out', route, nextAction: 'Maximum agent turns reached; resume after inspecting artifacts.' }));
      if (!this.adapter) {
        this.adapter = chooseAdapter(this.options.agent, { agentPath: this.options.agentPath });
        if (!this.adapter.ok) return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'failed', route, nextAction: 'Run replatform doctor and authenticate an installed supported agent.' }));
      }
      turns += 1;
      let directAgentId = null;
      this.child = launch(this.adapter.id, { cwd: this.projectDir, executablePath: this.options.agentPath, prompt: bootstrap(this.projectDir), onWorker: async (worker) => {
        let accepted = false;
        await this.updateTasks((state) => { const task = state.tasks.find((item) => item.state === 'running'); accepted = Boolean(task) && recordWorker(state, task.taskId, this.adapter.id, worker); });
        if (!accepted) await this.emit('protocol_error', 'running', 'Ignored malformed agent worker report.', { evidence: { kind: 'adapter_protocol', ref: this.adapter.id } });
      }, onEvent: async (event) => {
        this.lastObservationAt = Date.now();
        if (this.vendorEventsPath && event.type === 'vendor_event') await appendLine(this.vendorEventsPath, event.raw);
        await this.emit(event.type === 'vendor_event' ? 'progress' : 'progress', 'running', 'Observed agent output.', { evidence: { kind: event.type, ref: this.adapter.id } });
      } });
      await this.updateTasks((state) => {
        const task = startRoute(state, route);
        directAgentId = startDirectAgent(state, task, this.adapter.id, this.child.pid).agentId;
      });
      await this.writeRecord({ childPid: this.child.pid, childProcessGroup: this.child.pid });
      await this.emit('agent_started', 'running', `Started ${this.adapter.id} agent turn.`, { evidence: { kind: 'process', ref: String(this.child.pid) } });
      const childDone = this.waitForChild();
      const heartbeat = this.options.statusIntervalMs ? setInterval(async () => {
        const elapsed = Date.now() - this.lastObservationAt;
        if (elapsed >= this.options.statusIntervalMs) await this.emit('heartbeat', 'running', 'Agent process is alive; no newer progress was observed.', { lastObservedAt: new Date(this.lastObservationAt).toISOString(), elapsedSinceObservationMs: elapsed, evidence: { kind: 'process', ref: String(this.child?.pid) } });
      }, Math.max(1000, this.options.statusIntervalMs)) : null;
      let finished = null;
      // A second terminal communicates through the durable request file. Polling that
      // file is intentionally mundane: it works for foreground and detached ownership
      // without introducing a daemon socket or an interactive stdin channel.
      while (!finished) {
        finished = await Promise.race([
          childDone,
          new Promise((resolve) => setTimeout(() => resolve(null), 500)),
        ]);
        if (!finished && await this.cancellationRequested()) {
          if (heartbeat) clearInterval(heartbeat);
          return this.cancel(await this.cancellationRequested());
        }
        const wallExpired = this.options.wallTimeoutMs && Date.now() - this.startedAtMs > this.options.wallTimeoutMs;
        const idleExpired = this.options.idleTimeoutMs && Date.now() - this.lastObservationAt > this.options.idleTimeoutMs;
        if (!finished && (wallExpired || idleExpired)) {
          if (heartbeat) clearInterval(heartbeat);
          requestCancel(this.child);
          const stopped = await Promise.race([childDone, new Promise((resolve) => setTimeout(() => resolve(null), this.options.gracePeriodMs))]);
          if (!stopped) {
            try { process.kill(-this.child.pid, 'SIGKILL'); } catch { this.child.kill('SIGKILL'); }
          }
          return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'timed_out', route, nextAction: wallExpired ? 'The configured wall-clock timeout elapsed; inspect diagnostics and resume.' : 'Agent made no observable progress before the idle timeout; inspect diagnostics and resume.' }));
        }
      }
      if (heartbeat) clearInterval(heartbeat);
      this.child = null;
      await this.updateTasks((state) => finishDirectAgent(state, directAgentId, finished.code === 0 ? 'completed' : 'failed'));
      if (finished.code !== 0) return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'failed', route, nextAction: `Agent exited with ${finished.code ?? finished.signal}; inspect vendor diagnostics and resume.` }));
    }
    return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'timed_out' }));
  }

  async cancel(request) {
    await this.setOrchestrationCancellation('cancel_requested');
    await this.emit('cancel_requested', 'cancel_requested', request.reason || 'Cancellation requested.');
    if (!this.child) {
      await this.setOrchestrationCancellation('canceled');
      await this.emit('canceled', 'canceled', 'Cancellation confirmed; no active child remained.');
      return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'canceled', nextAction: 'Use replatform resume <project> when ready.' }));
    }
    requestCancel(this.child);
    const grace = request.gracePeriodMs || this.options.gracePeriodMs;
    const done = await Promise.race([this.waitForChild(), new Promise((resolve) => setTimeout(() => resolve(null), grace))]);
    if (done) {
      await this.setOrchestrationCancellation('canceled');
      await this.emit('canceled', 'canceled', 'Agent exited during cancellation grace period.');
      return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'canceled' }));
    }
    try { process.kill(-this.child.pid, 'SIGKILL'); } catch { this.child.kill('SIGKILL'); }
    await this.setOrchestrationCancellation('interrupted');
    await this.emit('interrupted', 'interrupted', 'Agent required forced termination.');
    return this.finish(makeResult({ id: this.id, projectDir: this.projectDir, outcome: 'interrupted' }));
  }
}

async function requestCancellation(projectDir, { reason = 'canceled by operator', gracePeriodMs = 60000 } = {}) {
  const active = await readActive(projectDir);
  if (!active || active.status !== 'running') throw new Error('no controllable active run exists');
  const request = { schemaVersion: SCHEMA_VERSION, runId: active.runId, requestedAt: iso(), reason, gracePeriodMs };
  await writeJsonAtomic(cancelPath(projectDir), request);
  return { active, request };
}

module.exports = { SCHEMA_VERSION, RunController, runnerDir, activePath, historyPath, defaultEventsPath, readActive, findRun, requestCancellation, applyInvocationInputs, makeResult, exitCode, safeRelative, readJson, userActionSummary };

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Wix
Publisher
Wix (Official)
Source
wix/skills · skills/wix-replatform · commit d168bc2
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Wix or Wix.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download wix-replatform.zip