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/url-redirect-plan.js

'use strict';

// Deterministic old-URL preservation planning.
//
// Input: the import's URL ledger (current source page addresses), source-authored redirect
// definitions, the website builder's final route manifest, the declared production origins,
// and (optionally) the destination site's current redirect inventory.
// Output: one obligation per known old address, and at most one remote rule per
// site + path + API scope. Nothing here writes, publishes or guesses: a missing or ambiguous
// destination is an obligation with a reason and an operator action, never a best guess.

const crypto = require('node:crypto');

const PLAN_SCHEMA_VERSION = 1;
const MAX_SOURCE_CHAIN_HOPS = 10;
const PLACEHOLDER_BASE = 'http://placeholder.invalid';

function sha256(value) {
  return crypto.createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex');
}

function stable(value) {
  if (Array.isArray(value)) return value.map(stable);
  if (value && typeof value === 'object') {
    return Object.keys(value).sort().reduce((out, key) => {
      if (value[key] !== undefined) out[key] = stable(value[key]);
      return out;
    }, {});
  }
  return value;
}

function digest(value) {
  return sha256(JSON.stringify(stable(value)));
}

// --- URL parsing ------------------------------------------------------------------------

// Structural parse of an old address. Reserved escapes such as %2F are kept as-is (never
// decoded), hex case is normalized, non-ASCII is percent-encoded, and the query/fragment are
// kept separately so they are never discarded.
function parseAddress(raw, { origins = [] } = {}) {
  if (typeof raw !== 'string' || !raw.trim()) return { ok: false, reason: 'malformed_url' };
  const value = raw.trim();
  if (/%(?![0-9A-Fa-f]{2})/.test(value)) return { ok: false, reason: 'malformed_encoding' };
  let url;
  let absolute = false;
  try {
    if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
      absolute = true;
      url = new URL(value);
    } else if (value.startsWith('//')) {
      return { ok: false, reason: 'scheme_relative_url' };
    } else if (value.startsWith('/')) {
      url = new URL(value, PLACEHOLDER_BASE);
    } else {
      return { ok: false, reason: 'not_site_relative' };
    }
  } catch {
    return { ok: false, reason: 'malformed_url' };
  }
  if (absolute && url.protocol !== 'http:' && url.protocol !== 'https:') return { ok: false, reason: 'unsupported_scheme' };
  if (url.username || url.password) return { ok: false, reason: 'credentials_in_url' };
  let origin = null;
  if (absolute) {
    const scheme = url.protocol.slice(0, -1);
    const port = url.port ? Number(url.port) : (scheme === 'https' ? 443 : 80);
    origin = `${scheme}://${url.hostname}:${port}`;
    const declared = origins.some((o) => `${o.scheme}://${o.hostname}:${o.effectivePort}` === origin);
    if (!declared) return { ok: true, external: true, origin, href: url.href };
  }
  const pathName = url.pathname.replace(/%[0-9a-f]{2}/gi, (m) => m.toUpperCase());
  return {
    ok: true,
    external: false,
    origin,
    path: pathName,
    conflictPath: conflictPath(pathName),
    query: url.search || '',
    fragment: url.hash || '',
  };
}

// Provider trailing-slash equivalence, applied only to redirect conflict keys.
function conflictPath(pathName) {
  if (pathName.length > 1 && pathName.endsWith('/')) return pathName.replace(/\/+$/, '') || '/';
  return pathName;
}

function isPathPrefix(prefix, candidate) {
  if (prefix === '/') return true;
  return candidate === prefix || candidate.startsWith(`${prefix}/`);
}

// --- remote identity -------------------------------------------------------------------

// The API stores one site-level rule per path; origins are not part of its identity.
function apiScopeOf(rule) {
  return {
    groupRedirect: Boolean(rule && rule.options && rule.options.groupRedirect),
    language: (rule && rule.language) || '*',
  };
}

function remoteRuleKey(siteId, fromConflictPath, scope = { groupRedirect: false, language: '*' }) {
  return `${siteId}|${fromConflictPath}|${scope.groupRedirect ? 'group' : 'exact'}|${scope.language}`;
}

function normalizeInventoryRule(rule) {
  const from = parseAddress(rule.from || '');
  const to = parseAddress(rule.to || '');
  return {
    id: rule.id || null,
    from: rule.from,
    to: rule.to,
    fromConflict: from.ok && !from.external ? from.conflictPath : null,
    toConflict: to.ok && !to.external ? to.conflictPath : null,
    toExternal: Boolean(to.ok && to.external),
    toQuery: to.ok && !to.external ? to.query : '',
    scope: apiScopeOf(rule),
  };
}

function inventoryDigest(inventory) {
  return digest((inventory || []).map((rule) => ({
    id: rule.id || null, from: rule.from, to: rule.to, scope: apiScopeOf(rule),
  })).sort((a, b) => `${a.from}|${a.to}|${a.id}`.localeCompare(`${b.from}|${b.to}|${b.id}`)));
}

// --- planning --------------------------------------------------------------------------

const ENTITY_URL_SKIP = new Set(['not_public', 'source_url_missing']);
// Import-era unresolved rows that a final route manifest is expected to settle. Any other open
// or manual_review row keeps its decision: the obligation stays manual_review, never a write.
const IMPORT_RESOLVABLE_STATUS = new Set(['target_url_missing', 'pending_target_route', 'redirect_required', 'preserved']);
// Only these documented routing uncertainties can be settled by an exact final route.
// Privacy, explicit decisions, missing reasons and all other causes remain restrictions.
const BASE_PATH_ROUTING_REASONS = new Set(['target_route_unknown', 'target_url_missing', 'pending_target_route', 'final_route_missing']);

function addReason(target, code) {
  if (!target.reasonCodes.includes(code)) target.reasonCodes.push(code);
}

function obligationKeyOf(parsed) {
  return `${parsed.path}${parsed.query}${parsed.fragment}`;
}

function buildEntityIndex(ledgerRows) {
  const byConflictPath = new Map();
  for (const row of ledgerRows) {
    if (ENTITY_URL_SKIP.has(row.urlStatus) || !row.sourceRelativeUrl) continue;
    const parsed = parseAddress(row.sourceRelativeUrl);
    if (!parsed.ok || parsed.external) continue;
    const list = byConflictPath.get(parsed.conflictPath) || [];
    if (!list.some((entry) => entry.sourceStableKey === row.sourceStableKey)) list.push(row);
    byConflictPath.set(parsed.conflictPath, list);
  }
  return byConflictPath;
}

function buildRouteIndexes(finalRoutes) {
  const bySourceKey = new Map();
  const byConflictPath = new Map();
  for (const route of (finalRoutes && finalRoutes.routes) || []) {
    const parsed = parseAddress(route.relativeUrl);
    if (!parsed.ok || parsed.external) continue;
    const entry = { ...route, conflictPath: parsed.conflictPath, path: parsed.path, query: parsed.query };
    bySourceKey.set(route.sourceKey, [...(bySourceKey.get(route.sourceKey) || []), entry]);
    byConflictPath.set(parsed.conflictPath, [...(byConflictPath.get(parsed.conflictPath) || []), entry]);
  }
  return { bySourceKey, byConflictPath };
}

function distinctRoutes(routes) {
  const seen = new Map();
  for (const route of routes) seen.set(`${route.targetEntityType}|${route.targetEntityId}|${route.conflictPath}`, route);
  return [...seen.values()];
}

// Follow enabled exact source rules to the current source entity whose page they reach.
function resolveSourceChain(startRule, ctx) {
  const visited = [];
  let rule = startRule;
  for (let hop = 0; hop <= MAX_SOURCE_CHAIN_HOPS; hop += 1) {
    visited.push(rule.ruleKey);
    const dest = parseAddress(rule.destination || '', { origins: ctx.origins });
    if (!dest.ok) return { status: 'manual_review', reason: `destination_${dest.reason}`, edges: visited };
    if (dest.external) return { status: 'manual_review', reason: 'external_destination', edges: visited };
    if (dest.query) return { status: 'manual_review', reason: 'destination_query_semantics', edges: visited };
    const entities = ctx.entityIndex.get(dest.conflictPath) || [];
    if (entities.length > 1) return { status: 'manual_review', reason: 'ambiguous_destination_entity', edges: visited };
    if (entities.length === 1) return { status: 'resolved', entity: entities[0], edges: visited };
    const next = ctx.exactRulesBySource.get(dest.conflictPath) || [];
    if (next.length > 1) return { status: 'manual_review', reason: 'conflicting_source_rules', edges: visited };
    if (next.length === 0) return { status: 'unresolved', reason: 'destination_not_found', edges: visited };
    if (visited.includes(next[0].ruleKey)) return { status: 'manual_review', reason: 'source_rule_cycle', edges: visited };
    rule = next[0];
  }
  return { status: 'manual_review', reason: 'source_chain_too_long', edges: visited };
}

function classifySourceRule(rule) {
  if (!rule.enabled) return 'disabled_rule_excluded';
  if (rule.matchType !== 'exact') return 'unsupported_match_type';
  // Only exact 301 rules can be written (the API takes an unqualified from/to rule). A 308
  // keeps the request method; rewriting it as a 301 would silently change its semantics.
  if (rule.statusCode === 308) return 'status_308_not_writable';
  if (rule.statusCode !== 301) return 'non_permanent_status';
  if (rule.language) return 'language_scoped_rule';
  if (Array.isArray(rule.conditions) && rule.conditions.length) {
    const onlyHost = rule.conditions.every((c) => c && c.type === 'host');
    if (!onlyHost) return 'conditional_rule';
  }
  return null;
}

function hostConditionOrigins(rule, origins) {
  const hosts = (rule.conditions || []).filter((c) => c && c.type === 'host').map((c) => String(c.value || '').toLowerCase());
  if (!hosts.length) return null;
  return origins.filter((o) => hosts.includes(o.hostname));
}

function planRedirects(input) {
  const {
    siteId,
    ledgerRows = [],
    sourceRules = [],
    importedRedirectOutcomes = [],
    coverage = null,
    finalRoutes = null,
    sourceDomains = null,
    targetInventory = null,
    importRedirects = [],
    invalidImportRedirects = [],
    importUnresolved = [],
    basePaths = [],
  } = input;
  const origins = (sourceDomains && sourceDomains.origins) || [];
  const originKeys = origins.map((o) => `${o.scheme}://${o.hostname}:${o.effectivePort}`);
  const deploymentId = finalRoutes ? finalRoutes.deploymentId : null;
  const ruleFindings = [];
  const importedByRule = new Map(importedRedirectOutcomes.map((row) => [row.sourceStableKey, row]));
  const capturedRuleKeys = new Set(sourceRules.filter((rule) => rule.enabled && rule.storage?.kind !== 'export')
    .map((rule) => `${rule.provider}:redirect:${rule.sourceRuleId || rule.stableId}`));
  const inventoryBySource = new Map();
  for (const rule of targetInventory || []) {
    const normalized = normalizeInventoryRule(rule);
    if (!normalized.fromConflict) continue;
    if (!inventoryBySource.has(normalized.fromConflict)) inventoryBySource.set(normalized.fromConflict, []);
    inventoryBySource.get(normalized.fromConflict).push({ rule, normalized });
  }

  // Source-rule inventory: deduplicate identical definitions across providers, keep evidence.
  const activeRules = [];
  const semantic = new Map();
  for (const rule of sourceRules) {
    const exclusion = classifySourceRule(rule);
    if (exclusion === 'disabled_rule_excluded') {
      ruleFindings.push({ ruleKey: rule.ruleKey, provider: rule.provider, disposition: 'excluded', reasonCodes: [exclusion] });
      continue;
    }
    const src = parseAddress(rule.source, { origins });
    const key = src.ok && !src.external ? `${src.conflictPath}${src.query}` : `raw:${rule.source}`;
    const signature = JSON.stringify([key, rule.destination, rule.statusCode, rule.matchType, rule.conditions || null, rule.language || null]);
    if (semantic.has(signature)) {
      semantic.get(signature).duplicateEvidence.push({ ruleKey: rule.ruleKey, provider: rule.provider, storage: rule.storage });
      continue;
    }
    const entry = { ...rule, parsedSource: src, exclusion, duplicateEvidence: [] };
    semantic.set(signature, entry);
    activeRules.push(entry);
  }
  const exactRulesBySource = new Map();
  for (const rule of activeRules) {
    if (rule.exclusion || !rule.parsedSource.ok || rule.parsedSource.external || rule.parsedSource.query) continue;
    const list = exactRulesBySource.get(rule.parsedSource.conflictPath) || [];
    list.push(rule);
    exactRulesBySource.set(rule.parsedSource.conflictPath, list);
  }

  const entityIndex = buildEntityIndex(ledgerRows);
  const entityTypesByKey = new Map();
  for (const row of ledgerRows) {
    if (!row.sourceStableKey || !row.sourceEntityType) continue;
    if (!entityTypesByKey.has(row.sourceStableKey)) entityTypesByKey.set(row.sourceStableKey, new Set());
    entityTypesByKey.get(row.sourceStableKey).add(row.sourceEntityType);
  }
  const routes = buildRouteIndexes(finalRoutes);
  const ctx = { origins, entityIndex, exactRulesBySource };
  const obligations = new Map();

  function obligationFor(parsed, rawUrl) {
    const key = parsed.ok && !parsed.external ? obligationKeyOf(parsed) : `refused:${rawUrl}`;
    if (!obligations.has(key)) {
      obligations.set(key, {
        obligationKey: key,
        originalUrl: rawUrl,
        path: parsed.ok ? parsed.path || null : null,
        conflictPath: parsed.ok ? parsed.conflictPath || null : null,
        query: parsed.ok ? parsed.query || '' : '',
        fragment: parsed.ok ? parsed.fragment || '' : '',
        provenance: [],
        origins: new Set(),
        targets: [],
        disposition: null,
        reasonCodes: [],
        expected: null,
        remoteRuleKey: null,
      });
    }
    return obligations.get(key);
  }

  function attachTarget(ob, entity, via, originSubset) {
    const types = new Set(entityTypesByKey.get(entity.sourceStableKey) || []);
    if (entity.sourceEntityType) types.add(entity.sourceEntityType);
    const resolvedEntity = { ...entity, sourceEntityType: types.size === 1 ? [...types][0] : null };
    ob.targets.push({ entity: resolvedEntity, via, origins: originSubset || originKeys });
    for (const key of originSubset || originKeys) ob.origins.add(key);
  }

  for (const row of ledgerRows) {
    if (ENTITY_URL_SKIP.has(row.urlStatus) || !row.sourceRelativeUrl) continue;
    const parsed = parseAddress(row.sourceRelativeUrl, { origins });
    const ob = obligationFor(parsed, row.sourceRelativeUrl);
    ob.provenance.push({ kind: 'entity_url', sourceStableKey: row.sourceStableKey, sourceEntityType: row.sourceEntityType, urlStatus: row.urlStatus });
    if (!parsed.ok) { addReason(ob, parsed.reason); continue; }
    // A recorded manual decision is never turned into an automatic write.
    if (row.urlStatus === 'manual_review') addReason(ob, 'import_manual_review');
    attachTarget(ob, row, 'entity_url');
  }

  // Replay import-era redirect requirements: each one stays an obligation for its entity even
  // when the ledger no longer lists that address. The final route decides the destination;
  // the import-era target is kept as evidence.
  for (const row of importRedirects) {
    // Source-authored exact rules also have their full semantics in sourceRules. Their
    // import-era relative plan is compatibility evidence, not a second entity owner.
    if (capturedRuleKeys.has(row.sourceStableKey)) continue;
    if (/:redirect:/.test(row.sourceStableKey || '')) {
      const parsed = parseAddress(row.sourceRelativeUrl, { origins });
      const ob = obligationFor(parsed, row.sourceRelativeUrl);
      ob.provenance.push({ kind: 'inactive_import_redirect', sourceStableKey: row.sourceStableKey,
        recordedDestination: row.targetRelativeUrl });
      addReason(ob, 'inactive_import_redirect_plan_requires_reconciliation');
      continue;
    }
    const parsed = parseAddress(row.sourceRelativeUrl, { origins });
    const ob = obligationFor(parsed, row.sourceRelativeUrl);
    ob.provenance.push({ kind: 'import_redirect', sourceStableKey: row.sourceStableKey, importTarget: row.targetRelativeUrl, status: row.status });
    if (!parsed.ok) { addReason(ob, parsed.reason); continue; }
    attachTarget(ob, { sourceStableKey: row.sourceStableKey, sourceEntityType: row.sourceEntityType || null }, 'import_redirect');
  }

  for (const row of invalidImportRedirects) {
    const source = row.sourceRelativeUrl || `redirects.ndjson line ${row.line}: address missing`;
    const parsed = parseAddress(source, { origins });
    const ob = obligationFor(parsed, source);
    ob.provenance.push({ kind: 'import_redirect_rejected', line: row.line, recordedDestination: row.recordedDestination || null, recordedStatus: row.recordedStatus || null });
    addReason(ob, row.reason || 'import_redirect_invalid_row');
    if (!parsed.ok) addReason(ob, parsed.reason);
  }

  // Replay import-era unresolved rows. Resolved rows are evidence only. Open rows that only
  // waited for a final route stay obligations; anything else keeps a manual decision.
  for (const row of importUnresolved) {
    const parsed = parseAddress(row.sourceRelativeUrl, { origins });
    const evidence = { kind: 'import_unresolved', sourceStableKey: row.sourceStableKey, urlStatus: row.urlStatus, status: row.status, reason: row.reason || null };
    if (row.status === 'resolved') {
      const key = parsed.ok && !parsed.external ? obligationKeyOf(parsed) : `refused:${row.sourceRelativeUrl}`;
      if (obligations.has(key)) obligations.get(key).provenance.push(evidence);
      continue;
    }
    const ob = obligationFor(parsed, row.sourceRelativeUrl);
    ob.provenance.push(evidence);
    if (!parsed.ok) { addReason(ob, parsed.reason); continue; }
    if (row.status === 'manual_review' || row.urlStatus === 'manual_review') addReason(ob, 'import_manual_review');
    else if (!IMPORT_RESOLVABLE_STATUS.has(row.urlStatus)) addReason(ob, `import_unresolved_${row.urlStatus}`);
    attachTarget(ob, { sourceStableKey: row.sourceStableKey, sourceEntityType: row.sourceEntityType }, 'import_unresolved');
  }

  for (const row of importedRedirectOutcomes) {
    if (row.disposition !== 'removed_input') continue;
    const parsed = parseAddress(row.originalSource || '', { origins });
    const remoteRuleExists = parsed.ok && !parsed.external &&
      (inventoryBySource.get(parsed.conflictPath) || []).length > 0;
    if (!row.requiresReconciliation && !remoteRuleExists) continue;
    const ob = obligationFor(parsed, row.originalSource || `removed:${row.sourceStableKey}`);
    ob.provenance.push({ kind: 'imported_redirect_removed', sourceStableKey: row.sourceStableKey,
      evidenceDigest: row.evidenceDigest });
    addReason(ob, 'removed_source_rule_requires_reconciliation');
  }

  for (const rule of activeRules) {
    const parsed = rule.parsedSource;
    const ob = obligationFor(parsed, rule.source);
    ob.provenance.push({ kind: 'source_rule', ruleKey: rule.ruleKey, provider: rule.provider,
      storage: rule.storage, stableId: rule.stableId, sourceRuleId: rule.sourceRuleId || rule.stableId,
      duplicates: rule.duplicateEvidence });
    ruleFindings.push({ ruleKey: rule.ruleKey, provider: rule.provider, disposition: 'obligation', obligationKey: ob.obligationKey, duplicates: rule.duplicateEvidence.map((d) => d.ruleKey), reasonCodes: rule.exclusion ? [rule.exclusion] : [] });
    if (!parsed.ok) { addReason(ob, parsed.reason); continue; }
    if (parsed.external) { addReason(ob, 'source_on_undeclared_origin'); continue; }
    if (rule.exclusion) { addReason(ob, rule.exclusion); continue; }
    if (parsed.query) { addReason(ob, 'query_conditional_rule'); continue; }
    const imported = importedByRule.get(`${rule.provider}:redirect:${rule.sourceRuleId || rule.stableId}`);
    const target = parseAddress(imported?.resolvedTarget || rule.destination || '', { origins });
    if (target.ok && target.external) {
      if (ob.externalTarget && ob.externalTarget !== rule.destination) {
        addReason(ob, 'conflicting_source_rules');
        continue;
      }
      if (!imported || imported.originalTarget !== rule.destination || imported.destinationKind !== 'external') {
        addReason(ob, 'external_destination');
        addReason(ob, 'external_target_audit_missing_or_stale');
        continue;
      }
      if (ob.targets.length || ob.provenance.some((item) => item.kind !== 'source_rule')) {
        addReason(ob, 'source_address_ownership_conflict');
        continue;
      }
      ob.externalTarget = imported.resolvedTarget || imported.originalTarget;
      ob.externalOriginalTarget = imported.originalTarget;
      ob.externalDisposition = imported.disposition;
      ob.externalEvidenceDigest = imported.evidenceDigest;
      continue;
    }
    const subset = hostConditionOrigins(rule, origins);
    if (subset && subset.length === 0) { addReason(ob, 'host_condition_undeclared'); continue; }
    const chain = resolveSourceChain(rule, ctx);
    ob.provenance[ob.provenance.length - 1].chain = chain.edges;
    if (chain.status !== 'resolved') { addReason(ob, chain.reason); ob.chainStatus = chain.status; continue; }
    attachTarget(ob, chain.entity, 'source_rule', subset ? subset.map((o) => `${o.scheme}://${o.hostname}:${o.effectivePort}`) : null);
  }

  // Import-era base-path decisions: a base path held for manual review, or recorded as not
  // public, is evaluated by reason for each matching occurrence. Unknown type cannot bypass it.
  const heldBasePaths = basePaths
    .filter((entry) => entry.status === 'manual_review' || entry.public === false)
    .map((entry) => ({ entry, parsed: parseAddress(entry.sourceBasePath) }));

  // Resolve each obligation's intended final page and whether a redirect is needed.
  for (const ob of obligations.values()) {
    if (ob.externalTarget) {
      if (ob.reasonCodes.length || !origins.length || ob.path === '/') {
        ob.disposition = 'manual_review';
        if (!origins.length) addReason(ob, 'origins_not_declared');
        if (ob.path === '/') addReason(ob, 'source_root');
      } else if (!['external_pending_execution', 'external_redirect_automation_unavailable'].includes(ob.externalDisposition)) {
        ob.disposition = 'manual_review';
        addReason(ob, ob.externalDisposition || 'external_target_not_ready');
      } else {
        ob.disposition = 'external_redirect';
        // The same-site API writer never accepts an external destination. A matching
        // inventory row is setup evidence only; public source verification is separate.
        const atSource = inventoryBySource.get(ob.conflictPath) || [];
        const matching = atSource.filter(({ rule, normalized }) =>
          !normalized.scope.groupRedirect && normalized.scope.language === '*' &&
          rule.to === ob.externalTarget);
        ob.externalSetup = matching.length === 1 ?
          { remoteId: matching[0].rule.id || null, target: matching[0].rule.to } : null;
        if (matching.length > 1) { ob.disposition = 'manual_review'; addReason(ob, 'external_setup_conflict'); }
        if (atSource.some((entry) => !matching.includes(entry))) {
          ob.disposition = 'manual_review'; addReason(ob, 'existing_rule_conflict'); ob.externalSetup = null;
        }
      }
      continue;
    }
    ob.origins = [...ob.origins].sort();
    const routingHolds = [];
    for (const { entry, parsed } of heldBasePaths) {
      const unknownType = !ob.targets.length || ob.targets.some((target) => !target.entity.sourceEntityType);
      if (!unknownType && !ob.targets.some((target) => target.entity.sourceEntityType === entry.sourceEntityType)) continue;
      if (!ob.conflictPath) continue;
      if (!parsed.ok || parsed.external) { addReason(ob, 'base_path_unparseable'); continue; }
      if (!isPathPrefix(parsed.conflictPath, ob.conflictPath)) continue;
      const reasons = Array.isArray(entry.reasonCodes) && entry.reasonCodes.every((code) => typeof code === 'string' && code.trim()) ? entry.reasonCodes : [];
      const hold = { kind: 'base_path_hold', sourceBasePath: entry.sourceBasePath,
        sourceEntityType: entry.sourceEntityType, reasonCodes: reasons, resolution: 'unresolved' };
      ob.provenance.push(hold);
      if (entry.public === false) { addReason(ob, 'base_path_not_public'); continue; }
      if (unknownType) { addReason(ob, 'base_path_entity_type_unknown'); continue; }
      if (!reasons.length) { addReason(ob, 'base_path_hold_reason_missing'); continue; }
      if (!reasons.every((reason) => BASE_PATH_ROUTING_REASONS.has(reason))) {
        addReason(ob, 'base_path_manual_review'); continue;
      }
      // Resolve only this occurrence, and only after the normal exact-route/ownership checks.
      routingHolds.push(hold);
    }
    if (!origins.length) addReason(ob, 'origins_not_declared');
    if (ob.path === '/' || ob.conflictPath === '/') addReason(ob, 'source_root');
    if (ob.reasonCodes.length) {
      const unresolvedOnly = ob.reasonCodes.every((code) => code === 'destination_not_found' || code === 'origins_not_declared');
      ob.disposition = unresolvedOnly ? 'unresolved' : 'manual_review';
      continue;
    }
    if (!finalRoutes) { ob.disposition = 'pending_website_build'; addReason(ob, 'final_routes_missing'); continue; }
    const entityKeys = [...new Set(ob.targets.map((t) => t.entity.sourceStableKey))];
    if (entityKeys.length !== 1) { ob.disposition = 'manual_review'; addReason(ob, 'conflicting_intended_entities'); continue; }
    const candidates = distinctRoutes(routes.bySourceKey.get(entityKeys[0]) || []);
    if (candidates.length === 0) { ob.disposition = 'unresolved'; addReason(ob, 'final_route_missing'); continue; }
    if (candidates.length > 1) { ob.disposition = 'manual_review'; addReason(ob, 'ambiguous_final_route'); continue; }
    const route = candidates[0];
    // The old address's query is part of what it means. A final route that carries its own,
    // different query leaves the expected result undefined, so a person decides.
    if (ob.query && route.query && ob.query !== route.query) { ob.disposition = 'manual_review'; addReason(ob, 'query_semantics_conflict'); continue; }
    ob.expected = {
      sourceKey: route.sourceKey,
      targetEntityType: route.targetEntityType,
      targetEntityId: route.targetEntityId,
      relativeUrl: route.relativeUrl,
      conflictPath: route.conflictPath,
      query: route.query || ob.query || '',
      pageMarker: route.pageMarker,
    };
    const owners = distinctRoutes(routes.byConflictPath.get(ob.conflictPath) || []);
    if (owners.some((owner) => owner.targetEntityId !== route.targetEntityId || owner.targetEntityType !== route.targetEntityType)) {
      ob.disposition = 'manual_review';
      addReason(ob, 'ownership_conflict');
      continue;
    }
    for (const hold of routingHolds) {
      hold.resolution = 'resolved_by_exact_final_route';
      hold.evidence = { sourceStableKey: route.sourceKey, targetEntityType: route.targetEntityType,
        targetEntityId: route.targetEntityId, relativeUrl: route.relativeUrl, deploymentId };
    }
    if (owners.length || route.conflictPath === ob.conflictPath) {
      ob.disposition = 'direct';
      continue;
    }
    ob.disposition = 'redirect';
  }

  // Fold per-origin intent into remote rules: one site-level rule per path and API scope.
  const remote = new Map();
  for (const ob of obligations.values()) {
    if (!ob.conflictPath || ob.conflictPath === '/' || !origins.length) continue;
    if (!['redirect', 'direct'].includes(ob.disposition)) continue;
    const key = remoteRuleKey(siteId, ob.conflictPath);
    if (!remote.has(key)) remote.set(key, { ruleKey: key, fromConflict: ob.conflictPath, from: ob.path, intents: [], obligationKeys: [] });
    const entry = remote.get(key);
    entry.obligationKeys.push(ob.obligationKey);
    for (const originKeyValue of originKeys) {
      const serves = ob.targets.some((t) => t.origins.includes(originKeyValue));
      entry.intents.push({
        origin: originKeyValue,
        obligationKey: ob.obligationKey,
        need: !serves ? 'none' : ob.disposition === 'direct' ? 'no_redirect' : ob.expected.relativeUrl,
      });
    }
  }

  const remoteRules = [];
  for (const entry of remote.values()) {
    const perOrigin = new Map();
    for (const intent of entry.intents) {
      if (!perOrigin.has(intent.origin)) perOrigin.set(intent.origin, new Set());
      perOrigin.get(intent.origin).add(intent.need);
    }
    // An origin with no obligation at this path has no requirement; an origin whose only
    // requirement is "none" while another needs a redirect blocks the whole key.
    const needs = new Set();
    const conflicts = [];
    for (const [origin, set] of perOrigin) {
      const concrete = [...set].filter((need) => need !== 'none');
      // A 'none' beside a concrete need means a second obligation at this path serves the
      // origin; only an origin with no concrete need contributes 'none'.
      if (concrete.length === 0) needs.add('none');
      else if (concrete.length > 1) conflicts.push({ origin, reason: 'conflicting_targets' });
      else needs.add(concrete[0]);
    }
    const rule = {
      ruleKey: entry.ruleKey,
      from: entry.from,
      fromConflict: entry.fromConflict,
      to: null,
      origins: [...perOrigin.keys()].sort(),
      obligationKeys: [...new Set(entry.obligationKeys)].sort(),
      disposition: null,
      reasonCodes: [],
      perOriginConflicts: conflicts,
    };
    if (conflicts.length) {
      rule.disposition = 'manual_review';
      rule.reasonCodes.push('origin_intent_conflict');
    } else if (needs.size > 1) {
      rule.disposition = 'manual_review';
      rule.reasonCodes.push('origin_intent_conflict');
      for (const [origin, set] of perOrigin) rule.perOriginConflicts.push({ origin, reason: `needs:${[...set].join(',')}` });
    } else {
      const only = [...needs][0];
      if (only === 'no_redirect' || only === 'none') {
        rule.disposition = 'no_write';
        rule.reasonCodes.push('route_serves_original_address');
      } else {
        rule.to = only;
        rule.disposition = 'write_candidate';
      }
    }
    remoteRules.push(rule);
  }

  // Whole-candidate-set checks: a destination that is itself a planned source would be a chain.
  const candidateSources = new Set(remoteRules.filter((r) => r.disposition === 'write_candidate').map((r) => r.fromConflict));
  for (const rule of remoteRules) {
    if (rule.disposition !== 'write_candidate') continue;
    const to = parseAddress(rule.to);
    rule.toConflict = to.ok ? to.conflictPath : null;
    if (!to.ok || to.external) { rule.disposition = 'manual_review'; rule.reasonCodes.push('invalid_destination'); continue; }
    if (to.conflictPath === rule.fromConflict) { rule.disposition = 'manual_review'; rule.reasonCodes.push('self_loop'); continue; }
    if (candidateSources.has(to.conflictPath)) { rule.disposition = 'manual_review'; rule.reasonCodes.push('candidate_chain'); }
  }

  const preflight = targetInventory ? preflightAgainstInventory(remoteRules, targetInventory, siteId) : null;
  const effectiveRules = preflight ? preflight.rules : remoteRules;

  // Blocked remote rules block every obligation they serve.
  const byRemote = new Map(effectiveRules.map((rule) => [rule.ruleKey, rule]));
  for (const ob of obligations.values()) {
    if (!ob.conflictPath) continue;
    const key = remoteRuleKey(siteId, ob.conflictPath);
    const rule = byRemote.get(key);
    if (!rule) continue;
    ob.remoteRuleKey = key;
    if (rule.disposition === 'manual_review' && ['redirect', 'direct'].includes(ob.disposition)) {
      if (ob.disposition === 'redirect' || rule.reasonCodes.includes('origin_intent_conflict')) {
        ob.disposition = 'manual_review';
        for (const code of rule.reasonCodes) addReason(ob, code);
      }
    }
  }

  const obligationList = [...obligations.values()].sort((a, b) => a.obligationKey.localeCompare(b.obligationKey));
  // The plan identity covers its inputs, not the live inventory: inventory drift is caught by
  // the apply-time preflight, while a changed ledger, rule set, route manifest, deployment or
  // origin list is a different plan.
  const planDigest = digest({
    siteId,
    deploymentId,
    origins: originKeys,
    ledger: ledgerRows.map((row) => [row.sourceStableKey, row.sourceRelativeUrl, row.sourceEntityType || null, row.urlStatus]),
    sourceRules: sourceRules.map((rule) => [rule.ruleKey, rule.enabled, rule.matchType, rule.source, rule.destination, rule.statusCode, rule.conditions || null, rule.language || null]),
    importedRedirectOutcomes: importedRedirectOutcomes.map((row) => [row.sourceStableKey, row.originalTarget, row.disposition, row.evidenceDigest]),
    routes: ((finalRoutes && finalRoutes.routes) || []).map((r) => [r.sourceKey, r.targetEntityType, r.targetEntityId, r.relativeUrl, r.pageMarker]),
    importRedirects: importRedirects.map((row) => [row.sourceStableKey, row.sourceRelativeUrl, row.sourceEntityType || null, row.targetRelativeUrl, row.status]),
    invalidImportRedirects: invalidImportRedirects.map((row) => [row.line, row.sourceRelativeUrl, row.reason, row.recordedDestination || null, row.recordedStatus || null]),
    importUnresolved: importUnresolved.map((row) => [row.sourceStableKey, row.sourceRelativeUrl, row.sourceEntityType || null, row.urlStatus, row.status]),
    basePaths: basePaths.map((entry) => [entry.sourceEntityType, entry.sourceBasePath, entry.sourceUrlPattern, entry.public, entry.status, entry.reasonCodes || null]),
  });
  const coverageRows = (coverage && coverage.providers) || [];
  return {
    schemaVersion: PLAN_SCHEMA_VERSION,
    planDigest,
    siteId,
    deploymentId,
    productionHostname: sourceDomains ? sourceDomains.productionHostname : null,
    origins: originKeys,
    websiteBuilt: Boolean(finalRoutes),
    coverage: coverageRows,
    coverageComplete: coverageRows.length > 0 && coverageRows.every((row) => row.status === 'extracted' || row.status === 'confirmed_empty'),
    obligations: obligationList.map((ob) => ({
      obligationKey: ob.obligationKey,
      originalUrl: ob.originalUrl,
      path: ob.path,
      query: ob.query,
      fragment: ob.fragment,
      origins: ob.origins.length ? ob.origins : originKeys,
      disposition: ob.disposition,
      reasonCodes: ob.reasonCodes,
      expected: ob.expected,
      externalTarget: ob.externalTarget || null,
      externalOriginalTarget: ob.externalOriginalTarget || null,
      externalDisposition: ob.externalDisposition || null,
      externalEvidenceDigest: ob.externalEvidenceDigest || null,
      externalSetup: ob.externalSetup || null,
      remoteRuleKey: ob.remoteRuleKey,
      provenance: ob.provenance,
    })),
    // Pre-inventory candidates: apply always re-runs the preflight against a fresh inventory.
    remoteRules,
    preflight,
    sourceRuleFindings: ruleFindings,
  };
}

// Compare candidate rules against the site's existing redirects. Exact semantic match is
// `already_present`; anything that could replace, delete or overlap an existing rule is
// `manual_review` with zero writes.
function preflightAgainstInventory(remoteRules, inventory, siteId) {
  const existing = (inventory || []).map(normalizeInventoryRule);
  const rules = remoteRules.map((rule) => ({ ...rule, reasonCodes: [...rule.reasonCodes] }));
  for (const rule of rules) {
    if (rule.disposition !== 'write_candidate') continue;
    const toConflict = rule.toConflict || parseAddress(rule.to).conflictPath;
    const block = (code) => { rule.disposition = 'manual_review'; if (!rule.reasonCodes.includes(code)) rule.reasonCodes.push(code); };
    for (const ex of existing) {
      if (!ex.fromConflict) continue;
      const exKey = remoteRuleKey(siteId, ex.fromConflict, ex.scope);
      if (exKey === rule.ruleKey) {
        if (!ex.toExternal && ex.toConflict === toConflict && !ex.toQuery) {
          rule.disposition = 'already_present';
          rule.remoteId = ex.id;
        } else block('existing_rule_conflict');
        continue;
      }
      if (ex.fromConflict === rule.fromConflict && ex.scope.language !== '*') block('language_overlap');
      if (ex.fromConflict === rule.fromConflict && ex.scope.groupRedirect) block('group_overlap');
      if (ex.scope.groupRedirect && ex.fromConflict !== rule.fromConflict && (isPathPrefix(ex.fromConflict, rule.fromConflict) || isPathPrefix(rule.fromConflict, ex.fromConflict))) block('group_overlap');
      if (ex.fromConflict === toConflict) block('destination_is_existing_source');
      if (ex.scope.groupRedirect && isPathPrefix(ex.fromConflict, toConflict)) block('destination_under_group_rule');
      if (ex.toConflict && ex.toConflict === rule.fromConflict) block('creates_chain_with_existing_rule');
    }
  }
  return { rules, inventoryDigest: inventoryDigest(inventory) };
}

module.exports = {
  PLAN_SCHEMA_VERSION,
  MAX_SOURCE_CHAIN_HOPS,
  parseAddress,
  conflictPath,
  remoteRuleKey,
  apiScopeOf,
  inventoryDigest,
  normalizeInventoryRule,
  planRedirects,
  preflightAgainstInventory,
  digest,
};

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