Rp Source Wordpress
WixOfficialPublished by Wix
- Skill
- Tool integration
- Software development
- MIT
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The rp-source-wordpress skill provides the necessary logic to interface with WordPress and WooCommerce REST APIs. It handles authentication, pagination, and schema capture, serving as a reference for discovery and code generation stages. By encapsulating platform-specific quirks, it allows the broader migration workflow to remain platform-agnostic while ensuring reliable data extraction.
What it does
- Captures WordPress and WooCommerce schemas and samples data for discovery.
- Manages authentication via Application Passwords for private data access.
- Provides logic for reading payment gateway configurations securely.
- Handles media URL resolution and product image confirmation.
- Automates plugin inventory detection and coverage reporting.
- Generates reader code for bulk data extraction.
When to use it
- When the source platform for a migration is identified as WordPress or WooCommerce.
- During the discovery phase to sample source data and generate a schema.
- When generating importers for bulk data extraction from a WordPress-based site.
- When auditing plugin coverage and payment gateway configurations.
Advantages
- Ensures platform-specific knowledge is isolated from the main migration workflow.
- Provides secure handling of sensitive credentials through a dedicated manager.
- Includes robust logic for resolving complex media and image references.
- Enforces strict data privacy by preventing the exposure of raw gateway settings.
Usage examples
- “Run the discovery process for a WordPress site.”
- The agent executes the discovery script to sample the REST index and generate a source profile and schema.
- “How do I handle WooCommerce payment gateway data?”
- The agent uses the gateway summary utility to report configuration status without exposing sensitive API keys.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/wix/rp-source-wordpress/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip rp-source-wordpress.zip -d .agents/skills
Documentation by Wix
rp-source-wordpress
WordPress / WooCommerce source adapter. Owns every WordPress-specific detail the platform-agnostic skills must not hardcode: how to capture the schema, how to read the data, auth models, pagination, and REST quirks.
When this skill is used
This is not a stage in the migration flow — it is a reference consulted by two stages:
rp-discoveryconsults the Capture section to sample the source and produce the canonicalsource-profile.md+source-schema.json.rp-import-codegenconsults the Read contract section to generate a reader that bulk-extracts WordPress data correctly (auth, pagination,wc/v3vswp/v2) into durable project-local files for the later import step.
rp-execute-import never consults this skill — by the time execution runs, the
WordPress-specific knowledge is already baked into the generated reader code. Keeping the
WordPress knowledge here is what lets the rest of the workflow stay platform-agnostic.
For app routing and internal-link reconciliation, the generated reader also enumerates the captured source roots, declared
source hosts, source permalink/alias evidence, and each record's containing source page.
It passes those facts to the shared internal-link-audit.js plan input after backend
import. Do not infer the containing page from a file basename or assume a default
WooCommerce path. The deterministic census records every captured file as scanned,
unreadable or unsupported; unsupported documents, dynamic URLs and missing captures
remain coverage items. Never scan config/*.env or execute captured source code.
Platform identity
Source platform: WordPress (core REST
wp/v2), optionally WooCommerce (wc/v3).Detect by hitting
<base-url>/wp-json/— the REST index lists advertised namespaces.Set
"platform": "wordpress"(and note WooCommerce presence insourceMeta) in the emittedsource-schema.json. This describes the discovery artifact, not the orchestration decision.Once discovery confirms WooCommerce, record
sourcePlatform.value=woocommerceinorchestration/decisions.jsonand useconfig/source.woocommerce.env. Otherwise recordsourcePlatform.value=wordpressthere and useconfig/source.wordpress.env. Generated importers read that exact nested value — never the decision wrapper object and never the nullableorchestration/run.jsonsourcePlatformfield. The adapter remainsrp-source-wordpressin both cases.
Capture (discovery-time)
Sampling the source to learn its shape — not a bulk export.
The Wix domain knowledge base may be used as a classifier supplement during synthesis,
but not as a sampling mandate. When a discovered WordPress/WooCommerce route matches a
known alias, annotate the emitted entity with sourceMeta.candidateTargetRefs[]; do not
turn that hint into a target decision here. Keep frontend, theme, runtime, admin, and
transient routes skipped by default even if a knowledge entry exists for a related
setup/config target.
After identifying the platform, verify migrations/<project>/config/source.<platform>.env.
For a confirmed WooCommerce source, this is source.woocommerce.env; for WordPress without
WooCommerce evidence, it is source.wordpress.env. Create the selected file if missing with
empty values:
WP_BASE_URL=
WP_USERNAME=
WP_APPLICATION_PASSWORD=
WP_MEDIA_URL_REWRITE_FROM=
WP_MEDIA_URL_REWRITE_TO=
WC_CONSUMER_KEY=
WC_CONSUMER_SECRET=Before requesting any WordPress / WooCommerce credentials for a URL-based migration, ask the user which data scope they want:
public content onlyalso include private/authenticated data
This choice is mandatory and must be explicit. Do not ask for WP_USERNAME,
WP_APPLICATION_PASSWORD, or WooCommerce keys until the user chooses also include private/authenticated data. Collect every sensitive
value through the secure Secrets Manager flow; do not ask the user to paste it into chat.
One credential covers both private WordPress/WooCommerce REST (wp/v2, wc/v3) and
wix-wp-plugin-v2 bridge reads: a WordPress Application Password (WP_USERNAME +
WP_APPLICATION_PASSWORD) for an administrator or a WooCommerce shop manager. The bridge
(0.5.0+) admits manage_options or manage_woocommerce, so it works with or without
WooCommerce; it has no key of its own. A site without WooCommerce running a bridge copy older
than 0.5.0 answers 403 to every user; discovery reports bridge_plugin_update_required --
ask the site owner to upload the current zip. An old env file that still has
WMH2_MIGRATION_KEY is harmless: the value is ignored.
Key sensitivity is predefined and does not change at runtime. Requiredness is separate and may depend on the selected acquisition mode or source behavior.
| Key | Sensitivity | Requiredness |
|---|---|---|
WP_BASE_URL | non-sensitive | Required for URL-based capture |
WP_USERNAME | sensitive | Required for private/authenticated WordPress capture via Application Password |
WP_APPLICATION_PASSWORD | sensitive | Required for private/authenticated WordPress capture via Application Password |
WP_MEDIA_URL_REWRITE_FROM | non-sensitive | Optional |
WP_MEDIA_URL_REWRITE_TO | non-sensitive | Optional |
WC_CONSUMER_KEY | sensitive | Optional unless WooCommerce rejects the WordPress Application Password for wc/v3 reads |
WC_CONSUMER_SECRET | sensitive | Optional unless WooCommerce rejects the WordPress Application Password for wc/v3 reads |
Required for a complete WordPress/WooCommerce capture:
WP_BASE_URLWP_USERNAME+WP_APPLICATION_PASSWORDwhen private REST-visible data is in scope
WC_CONSUMER_KEY and WC_CONSUMER_SECRET are optional when WooCommerce accepts the
WordPress Application Password for wc/v3 reads; ask for them only if WooCommerce routes
return 401/403 with the WordPress Application Password.
WP_MEDIA_URL_REWRITE_FROM and WP_MEDIA_URL_REWRITE_TO are optional. Use them when the
WordPress API is reached through a public tunnel but media/file URLs inside records still
point at localhost or another private origin. If they are blank, generated readers may
rewrite localhost/private origins to WP_BASE_URL when WP_BASE_URL is public.
config/source.<platform>.env is a secret-bearing file once it may contain real values.
Do not read it with whole-file commands that print its contents into tool output. Check
only whether the file exists and whether each required key is present/blank/missing; when
describing status, name keys only and never echo values.
Run the deterministic capture script from this skill's directory (the folder containing this
SKILL.md; seeCONVENTIONS.md):node scripts/wp-discovery.js --env-file <migrations-root>/<project>/config/source.<platform>.env --out-dir <migrations-root>/<project>/data/wp-discoveryIt walks the REST index, runs one
OPTIONS+ a smallGETsample per entity, and writes per-entity markdown (routes, schemas, sample records, record counts, relationships).--env-fileis the preferred launch path for project-local credential-bearing config because it avoids shell sourcing of secret-bearing files. Pass direct auth options only when there is no project-local config yet. For long runs, pass--progress-log <path>and poll it perCONVENTIONS.md#progress-log-polling.If the user chose
public content only, run unauthenticated and keep the scope framed as public-only. Do not pivot into asking for credentials unless the user changes scope.Credentials are required for a complete capture. Without auth, only published public content is reachable; drafts, WooCommerce (
wc/v3), user PII, and private fields return 401/403, making theirrecordCount/inUseunreliable. The script flags this in its README under "Incomplete Capture (Authentication)" — do not treat an unauthenticated run as authoritative.Author identity is a specific casualty of public-only capture. Public
/wp/v2/userslists only users who authored public posts and exposes norolesand no emails — admin vs editor vs contributor vs subscriber is indistinguishable. Roles/capabilities requirecontext=edit(App Password withlist_users) or a DB dump (wp_usermeta→wp_capabilities); WXR exports carry author login/email/display name but no roles either. Vanilla WP has no guest-byline concept (every byline is a user); plugin guest authors (Co-Authors Plusguest-authorentities) are separate non-user records. Record author capture mode in the source profile — it determines the blogauthorAttributionModedownstream (public-only → fallback/owner attribution; authenticated → per-author mapping: administrators → owner user-member, content roles → per-author members; subscribers/customers → Wix contacts by default — a contact is the no-login CRM person entity and Contacts V5 upserts in bulk — promote to full site members (1/sec serial, re-registration) only when member-gated features are in scope. Every Wix member auto-creates its contact, so member-first ordering: never pre-create a contact for someone who will become a member. Note contacts cannot author blog posts or comments — bylines need members).Distinguish supported entities (advertised by the REST index) from used entities (those with
recordCount > 0). Entities advertised but empty should be flagged, not mapped as if they hold data.Backend data scope. The capture script classifies REST routes before per-route
OPTIONSor sampleGETrequests. By default it samples backend data routes and skips frontend, theme/editor, runtime session, admin dashboard, diagnostics, marketplace setup, and integration/helper APIs. It writes the skipped-route audit trail toskipped-routes.json.It also always writes
source-coverage.json(rows: []when clean): one row per entity whose data request returned 401/403 (auth-gated) or failed with no records (an OPTIONS-probe failure alone is not one), per backend data route skipped by rule, per credential-bearing route never read (not-recoverable), and per unsupported route namespace. Frontend, theme, admin and transient skips get no row.rp-discoverypromotes it; never edit it by hand.For WooCommerce, prefer canonical durable data APIs such as
wc/v3over duplicatedwc/v2/wc/v1routes for authenticated/private commerce reads. Forpublic content onlydiscovery, probe public Store API catalog routes before declaring commerce deferred:wc/store/v1/productsandwc/store/v1/products/categoriesare in-scope public commerce data when present. Cart and checkout Store API routes remain out of scope as runtime session state.Images: never read a field, always resolve. An image reference in a WordPress-family payload is a set of candidate URLs for one picture — the merchant's original upload plus the crops WordPress generated from it. Which field holds the original varies by route, and the two WooCommerce APIs disagree on the same site: on
wc/store/v1images[].srcis the original, while onwc/v3it is resolved through WordPress's registered image sizes and can be the smallest crop, because any theme or image-optimizer plugin may redefine those sizes. Pass the whole reference toresolveImageUrl/resolveImageUrlsinlib/wp-image-url.jsand use what it returns. It handlessrc,thumbnail,source_url,srcset,thumbnail_srcset, andmedia_details.sizes.*, prefers the original, falls back to the widest crop, percent-encodes the result, and retains the attachment id assourceIdfor the media-record check below.Product pictures require source-record confirmation in generated imports. For the exact orchestration identities
woocommerceandwordpress, resolving the product reference is only the first step. Vendor/use the shared rootlib/confirmed-pictures.js: collect the selected products' distinct positivesourceIdvalues, callreadSourceMediaRecords({ ids, source: { baseUrl, request: authenticatedWpRequest } }), where that wrapper delegates tofetchJsonwith the run's existing auth headers, then pass each whole resolved gallery toconfirmPictures. The read requests authenticatedGET /wp/v2/media?include=<ids>&per_page=100chunks in sorted groups of at most 100; each chunk has one total 60-second transport deadline. The media record'ssource_urlis the evidence. Never infer an original from the filename and never construct a lookalike read or confirmed list: provenance is private to the shared module.A picture with no positive attachment id, no returned media record, or a media record in an unreadable chunk is unconfirmed (
no-source-id,no-source-record, orsource-unreadable). One unconfirmed picture defers the entire product gallery; continue with non-media product fields and followrp-import-codegen's ledger/recovery contract. Quick mode is unchanged and does not use this boundary.Inline post images resolved to media records. When an extractor maps an inline
<img>in post content to itswp/v2/mediarecord, look up thewp-image-<id>attachment id first (include=<ids>&per_page=100chunks). A filenamesearchfallback must read every page (per_page=100up toX-WP-TotalPages, or until a short page): a common filename stem returns more than one page, and a capped search silently drops the image. Compare the record'ssource_urlwithsameImageUrlfromlib/wp-image-url.js, never raw string equality: post HTML andsource_urlcan differ only in percent-encoding (non-Latin filenames). An image still unmatched is listed as unresolved in the extract manifest, never dropped.⚠️ This is not optional on the public path just because
srchappens to be right there today. Same call, everywhere — a contract test pins the Store API no-op, so a change in that behaviour surfaces as a test failure rather than as a merchant's blurry storefront.⚠️ The destination gives one attempt. Wix copies the single URL you send and generates every derivative from it, with no way to raise quality afterwards, so a crop shipped here is that product's permanent ceiling. When
resolvedIsCrop()is true the source genuinely had nothing better — report those images in the run's own record rather than shipping them silently.Plugin coverage runs automatically. Plugin handling is a deterministic pre-pass plus declarative profiles, not prose guesswork — see "Plugin coverage" below. The capture script writes
plugin-inventory.jsonandplugin-coverage.jsonalongside the per-entity files. Never hand-map a plugin from memory; consult the profiles throughscripts/plugin-knowledge.js.Localhost sources and media URLs. A source at
localhost,127.0.0.1, or another private-only host is valid for discovery and source reads from the user's machine. However, Wix Media import fetches files from the URL using Wix servers, so media URLs likehttp://localhost:8090/wp-content/uploads/...are not reachable by Wix during a live import. This is optional setup and, as far as we know today, only affects media import:Prefer exposing the local source through a temporary public HTTPS tunnel such as ngrok before live media import.
Or explicitly skip/defer media import and continue with non-media entities.
If using ngrok on macOS:
Install:
brew install ngrokAdd an authtoken from the ngrok dashboard:
ngrok config add-authtoken "<YOUR_AUTHTOKEN>"Expose the local source port, for example:
ngrok http 8090Set the source base URL to the HTTPS forwarding URL:
export WP_BASE_URL=https://<id>.ngrok-free.appRecord this insource-profile.mdwhen the captured source URL is localhost, and note whether media will use the tunnel or be skipped/deferred.
The raw capture is evidence, not a hand-off artifact. rp-discovery synthesizes it into
the canonical artifacts and records traceability pointers (rawDiscovery, per-entity
rawFile).
Payment gateways: read the summary, never the route
GET /wc/v3/payment_gateways and /wc/v3/payment_gateways/{id} return each gateway's entire
settings object. On a site with a real gateway connected that includes the live API key and
secret. Anything a tool returns is in the model's context, the transcript and potentially a
durable run artifact, so there is no careful-handling mitigation available after the fact — the
value must never be requested.
fetchGatewaySummary() in lib/wp-http.js is the only way to read gateway configuration.
It returns, per gateway, id / title / enabled / order and fields: [{ name, state }],
where state is present, blank or absent — plus a value for the short allowlist of
display and behaviour fields, each of which passes the shared secret-value guard first. That is
everything discovery legitimately needs: which gateways are registered, which are enabled, and
whether a credential is configured. Request-level outcomes (ok, unauthorized, unreachable,
malformed) are a separate axis, and a failed request returns zero field entries rather
than a page of absent, so "this gateway has no API key" can never be confused with "we could
not ask".
Everything else about the route is closed, on purpose:
fetchJson()refuses either gateway route before issuing the request, below discovery's--include-routeoverride. There is no flag, option, capability token or environment variable that lifts it; adding one is the exposure with extra steps.The route classifier categorizes both shapes as
excluded_credential_bearing, and neither--include-routenor--include-excluded-categorycan promote them tosample.A plugin profile may not declare a gateway route as a readable entity route, under any flag.
Never write a gateway field value into
source-profile.md,source-schema.json, a sample record, a progress log, a completion report, a CMS field, telemetry, or.local.env. Never a prefix, a length or a hash of one either — each of those is a usable clue on its own.
Report what was read. A run that states "N gateways, M enabled, K credential fields present, 0
values retained" is auditable; one that silently read the settings blob is not.
describeGatewaySummary() produces that line for the approval gate.
⚠️ The value guard is a pattern list, not a guarantee — a credential in an unrecognized format passes it. It is the backstop for credentials nobody can name in advance; the controls above are the actual protection.
Reading payment, refund and invoice history
Three deterministic registries carry this knowledge. Use them; do not re-derive which source keys mean what, and do not hand-author the reads.
| What you need | Use |
|---|---|
| Which source keys the payments import may read at all | paymentReadKeys() in lib/gateway-source-keys.js |
| Which value may become a payment's provider transaction reference | resolveTransactionReference() in the same module |
| Whether a method is online or offline | resolveOfflinePayment() — omits the flag when unknown |
| Whether a refund actually happened | qualifyRefund() in lib/refund-corroboration.js |
| Whether the store has invoices, and where their bytes live | lib/invoice-discovery.js |
The read manifest is closed. paymentReadKeys() returns the complete set of keys this import
touches — the amount, both paid-date fields, the method, the currency, the canonical reference,
and each registry family's candidate fields. Nothing else is read. In particular a raw provider
response blob is declared unreadable, not "to be pattern-matched later": on a live store its
sibling fields carried customer name, phone and email, and a contract that requires parsing
unstructured personal data is not one that can be honoured safely.
assertNoNeverReadKeys() refuses a read plan naming it before the plan executes — filtering
after the response arrives is too late, the blob is already in the run's working data.
Two surfaces, and neither alone covers payments. Row-shaped tables come through the plugin
/query surface; meta-backed fields come through WooCommerce REST. Run the generated
…--<table>.eav-read-plan.json verbatim and reconcile it afterwards — a hand-authored scoped read
cannot be reconciled against anything, and a plan edited after discovery wrote it is caught by its
own hash.
A gateway-shaped key is not attribution. The payment-method slug names the checkout plugin, not necessarily the processor: orders whose method is one gateway can carry another gateway's reference key, while every order whose method was that second gateway carried none. So a candidate is written only when its semantics are verified AND the registry recognizes the order's method — directly, or through a separately verified layered integration. Everything else is reported with a reason and never guessed at by precedence. Report candidate coverage and defensible coverage as separate numbers; collapsing them overstates fidelity.
A refund needs a refund record. A canonical WooCommerce refund entity with a stable id and a positive amount is authoritative on its own. An order-level refunded status corroborates but cannot supply a missing amount. Gateway flags, statuses and refundable-balance fields never create a refund, however many agree — fields written by one callback are one signal. When only such flags and statuses exist, this yields zero importable refunds, which is the correct output.
Invoices are resolved per run. Discovery matches key families, not authored names, and patterns found in a sample are then applied across the full order population. A discovered document URL is untrusted input that something is about to fetch: classify it before touching it, and never log or store it — the query string can be a bearer token and the filename can carry the customer's name. Nothing found means nothing is created, and the report says "no invoices found", never "not supported".
Redaction counts are findings, not plumbing: a non-zero redactedValueCount means a credential
was sitting somewhere unexpected in the source, and it belongs in the run report. Telemetry
carries counts only — never a discovered key name and never a value.
Plugin coverage
A real WooCommerce site is mostly plugins. Handling them is deterministic and has its own
knowledge base: plugins/ (profiles + no-migration-needed.json + README.md), read through
scripts/plugin-knowledge.js, detected by scripts/wp-plugin-inventory.js.
Every installed plugin lands in exactly one of the four statuses, and every status produces a row the user sees. Nothing is silently ignored.
| Population | Evidence | Result |
|---|---|---|
| recognized | a profile matched | named entities, declared read channels, Wix target refs; mapping confirmed |
| derived | no profile, data is REST-visible | derived from wp/v2/types + wp/v2/taxonomies, mapping proposed (CMS, or native on a domain-KB match) |
| derived (bridge) | no profile, the plugin's own tables read under a project-local plan | one derived:<plugin> row from the canonical plugin.<slug>.<entity> entities, mapping proposed (native on a domain-KB match, with cms/data-item offered beside it) |
| named only | detected, no read channel | Pending with its reason, resolved by the no-migration-needed list or at the review gate |
A plugin therefore does not need a profile to migrate — it needs one to migrate natively.
Detection
Runs before route classification so profile-declared routes are already in scope. Signals, strongest first:
GET /wp/v2/plugins— the authoritative installed list (plugin,status,name,version). Administrator credential required. On 401/403 the run continues and recordspluginListAvailable: false; say so plainly rather than implying full coverage. Without it, installed-but-unprofiled plugins cannot be enumerated at all — this is the concrete argument for the authenticated acquisition mode.Declared routes present in the REST index.
GET /wp/v2/types/GET /wp/v2/taxonomiesentries matching a profile'srestBases.Record payload keys from the samples — a second pass after sampling. This is not optional polish: several major WooCommerce extensions (Product Bundles, Composite Products, Product Add-Ons, ACF, Yoast) add no REST route at all and only widen
wc/v3/products/wc/v3/orderspayloads. Route-based discovery cannot see them.REST namespaces and public
/wp-content/plugins/<slug>/asset paths (low confidence, but they work with no credentials).
A plugin version below a profile's detect.minVersion is reported as
api-below-min-version, not read as if the documented API were present.
Project-local plugin entity plans
For an unfamiliar plugin, prefer a complete supported REST reader. If it is unavailable, investigate verified storage and use PLUGIN-READ-PLANS.md's shared validator/writer, including stable entity references, scoped related records and a bounded sample. A permanent profile or new transport handler is not required. Preserve the plan binding in canonical source metadata; only reconciled full extraction certifies readiness. Never return an ineffective “rerun discovery” task when a producer cannot emit its input.
Read channels
plugin-rest, core-cpt, core-embedded, core-meta, plugin-rest-child, export-file,
db-only — see plugins/README.md. Two consequences worth stating to the user:
Unregistered post meta is invisible to the REST API. WordPress exposes meta only when the plugin registered it with
show_in_rest(and, for a CPT, declaredcustom-fieldssupport). A plugin can keep its entire per-record state inpostmetaand expose none of it. Three ways to reach it, in preference order: the structure bridge (see "Reading key/value tables through the bridge" below — this is the one that needs no profile and no user action), a WXR export the user produces, or a database dump.WXR cannot be fetched. Application Passwords authenticate the REST API and XML-RPC only, never
wp-admin, so an export file is something the user produces and supplies. Treatexport-fileas a request to the user, never as a download.
Source redirect maps
Old addresses kept alive only by redirect rules must be inventoried; an empty REST answer or
the route classifier's /redirection/* exclusion is never evidence that no rules exist.
lib/wp-redirect-sources.js normalizes them from the plugins' own storage:
Redirection —
redirection_items+redirection_groupstables; Rank Math —rank_math_redirections(PHP-serializedsources, one rule per pattern). Read them through the structure bridge by bare table name;resolveTablematches the site's real prefix from the bridge's table listing and reports several matches (multisite) as ambiguous.Yoast Premium keeps redirects in
options, which stays denied: coverage isunsupporteduntil the operator supplies the plugin's CSV export.Server/CDN rules (
.htaccess, nginx, edge) live outside WordPress: record them asunsupportedand ask the host for an export.Logs, 404 records and hit counts are not rules. Disabled rules and rules of an inactive plugin are kept as
enabled: falseexclusions, never reactivated.A failed, partial or channel-less read is
unreadable, neverconfirmed_empty.
Capture is automatic. The providers are plugin profiles (an entity with a redirectSource
block; see plugins/README.md). When discovery detects one, it reads the declared tables in
full through the bridge (paged to completion), normalizes them and appends
state/url-preservation/source-redirects.ndjson and writes source-redirect-coverage.json;
the plugin-coverage row reports the captured rule count, or an operator action when the read
is not complete. Do not probe the tables by hand.
For an operator-supplied export (Yoast Premium, or a failed bridge read), feed it to
node skills/wix-replatform/scripts/url-redirects.js sources --project <dir> --input <file.json>; it records the capture the same way. When declared source domains are present, it also
plans the captured destinations into the redirect audit and URL rewrite report. If domains
are declared later, run url-redirects.js import-targets --project <dir> after that
declaration. Capability evidence for a specific rule can be supplied in the source input's
targetCapabilities[ruleKey] with productSupported, optional automationSupported, and
an evidence reference; absent evidence remains unverified where product support is not
established for that rule shape. A complete capture records a disabled tombstone for a
previously captured rule that disappeared, so the cutover report keeps its old address
open for explicit redirect reconciliation. Partial or unreadable captures never retire
missing rules.
Reading key/value tables through the bridge
When wix-wp-plugin-v2 is installed on the source site, postmeta and every other
key/value-shaped table is readable — key-scoped. This is the channel to reach for when a
capability would otherwise be a user-file blocker, and it is the ONLY one that works for a
plugin nobody has profiled.
Always run key discovery, even for a profiled plugin. It is tempting to treat a profile's
detect.recordProperties as the key list and skip the round-trip — subscriptions-for-woocommerce.json
names _wps_sfw_product there — but those are detection markers, one or two keys that prove
the plugin wrote the record. They are not the record's field list. Reading only them produces a
short extraction that looks complete, the same failure as a truncated key list.
Profiles earn their place elsewhere: they say which table to read, which entity it maps to, and what the pitfalls are. The key list comes from the site. A single order on a gateway-backed store can carry dozens of gateway-specific meta keys under a prefix no profile anywhere has seen, which is why discovery is the mechanism and not the fallback.
The rule: if you have not named the keys you want, the value column does not exist. Not
in select, not in where, not in orderBy, not in groupBy. Violating it returns
wmh2_invalid_structure_request (400) — the same error as naming a nonexistent column, so
the refusal will not tell you which column is the value column. Two steps:
GET /structure?table=postmeta→ the column list pluseavPair: {keyColumn, valueColumn}. This tells you the table is key-scoped before you write a query. No rows, no key names.Discovery —
selectthe key column plus a count,groupBythe key column. Returns the real key list with row counts,eavAccess.tier: "key-discovery".Scoped read —
wherethe key columninthe keys you want (max 50 per request), thenselectthe value column freely.eavAccess.tier: "key-scoped".
// 2. discovery // 3. scoped read
{"structureRequest": { {"structureRequest": {
"table": "postmeta", "table": "postmeta",
"select": [{"column": "meta_key"}, "select": [{"column": "post_id"},
{"column": "meta_key", {"column": "meta_key"},
"aggregate": "count", "as": "n"}], {"column": "meta_value"}],
"groupBy": ["meta_key"], "where": [{"column": "meta_key", "op": "in",
"orderBy": [{"column": "meta_key", "value": ["<key from step 2>",
"direction": "asc"}] "<key from step 2>"]}],
}} "orderBy": [{"column": "post_id", "direction": "asc"}]
}}⚠️ Count the KEY column, not some other column. {"column": "<keyColumn>", "aggregate": "count"} works on any key/value table; counting meta_id only works where that column happens
to exist, and a name/value table has no meta_id at all. The generic client counts the
discovered key column for exactly this reason.
Things that will bite:
Page discovery to exhaustion.
limitmaxes at 200 and a largepostmetahas more distinct keys than one page. FollowpagingMetadata.cursors.nextuntil it is null before concluding a key is absent — a truncated key list reads as "these are all the keys" and will send the mapping down a wrong path. Budgetceil(N/200)discovery pages plus at leastceil(N/50)scoped batches — and a batch is not a request: each pages at 200 rows, so a batch whose 50 keys hold 4,000 rows costs 20 requests. Because discovery returns each key's row count, the read plan states the real figure (expectedPagesper batch,expectedScopedRequestsoverall) — read it there rather than estimating.optionsandusermetaare still refused outright, and pinningoption_namedoes not unlockoptions. Gateway configuration held inoptionsis a different mechanism entirely — do not try to route around this.Check
redactionMetadata.redactedValueCounton every response. Non-zero means a value matched a credential shape and came back as[REDACTED:secret-shaped]. That is not a bug to work around: it means the source site keeps a credential somewhere unexpected, and it belongs in the run's notes.A table named
*metawhose pair is not one of the six recognized ones is refused (403), not readable. There is no key column to pin, so there is nothing to scope. Reach for a WXR export or a database dump for that table, and say so rather than reporting it as empty.A table can carry MORE than one pair, and each is guarded separately: pinning
meta_keydoes not make a second pair'svaluecolumn readable.eavPair.additionalPairsandeavAccess.additionalPairslist them;guardedValueColumns()in the client returns all of them at once, which is what you want when building a select list.Every value comes back as a STRING — including flags, ids and counts. A column the plugin stores as an integer flag arrives as
"0"or"1", andBoolean("0")is true in JavaScript, so the natural-lookingif (row.is_spam)classifies every row as spam. A form-submission import that reads a plugin'sis_spamcolumn straight into a truthiness test mismarks the entire set, and nothing errors: the run simply reports every row as spam. Compare explicitly (row.is_spam === '1', orNumber(row.is_spam) === 1) on every flag, id and numeric column you branch on, and never feed a bridge value to a bare truthiness test. The same holds for text-valued status columns:"active"is a string the plugin chose, not a normalized enum — and note that a source's own spam/status flags being uniformly clean is not evidence the data is clean, only that the source never flagged it.A submissions table shared by every form needs the source form id on BOTH sides. Form plugins that keep one entries table (Forminator's is the shape seen live; see
plugins/forminator.json) key each row by the source form id, while the target form ids are minted per form by the forms import. That is two lookups, not one: filter the source rows to the form being imported, and resolve that same form's crosswalked target id. Getting either side wrong writes real submissions onto the wrong target form and the create still succeeds — there is no error to notice. Assert the source-form-id → target-form-id pairing from the crosswalk before the first write, and read one created submission back on the form you expected it to land on.
Yoast product SEO evidence
WooCommerce product yoast_head_json is rendered output, never proof of an override (a store
can render a title on every product while holding no raw title override). Decide each product's SEO title,
description and focus keyphrase per field with lib/yoast-product-seo-evidence.js:
REST
metaon the product post (/wp/v2/product/{id}?context=edit): a key counts only whenmetacontains it (restEvidence). Missing key means unresolved, not "no override".Bridge key-scoped
postmetaread for keys still unresolved (readBridgeEvidence, withqueryPagebound toqueryStructure). It pins exactly_yoast_wpseo_title,_yoast_wpseo_metadesc,_yoast_wpseo_focuskwplus a batch of product ids, and pages tohasNext: false. This is the one deliberate exception to "always run key discovery": the key set is a fixed allow-list, never widened, and a complete scoped read with no row is itself the evidence (inherit). A failed, truncated or non-key-scoped batch makes only that batch's unresolved fieldsunknown.Otherwise
unknown. A user-supplied export can later provide evidence through the blocked-data request flow.
buildProductSeoReceipts returns the audit receipt per product (stored with the extraction,
never hashed whole); seoEvidenceFromReceipt gives the canonical product.seoEvidence. Never map
yoast_head_json.title/description, og_* or the excerpt into seoTitle/seoDescription.
Non-Yoast SEO plugins have no evidence contract: their product SEO is unknown.
Parent-scoped sub-resources (
plugin-rest-child, fixed 2026-08-11). WooCommerce order notes (/wc/v3/orders/{id}/notes) and similar per-parent sub-collections cannot be listed on their own — the base classifier only samples flat collection routes (page/per_pageshape). This is why a plugin that writes real data via$order->add_order_note(...)(e.g. Custom Payment Gateway for WooCommerce's payment-note field) used to report aspending · cannot-telleven though the data is real and REST-reachable in principle.plugin-rest-childfixes this: an entity declaresrouteas a{parentId}-templated path (/wc/v3/orders/{parentId}/notes) plusparentRoute(the already-sampled collection that supplies real parent ids, e.g./wc/v3/orders). Availability is a two-part presence check against the site's REST index —parentRouteis in scope, and the index advertises a route shaped like the template (WordPress's(?P<id>[\d]+)-style regex segments are normalized to{parentId}for the comparison, so the parameter's name never has to match). Presence alone does not confirm real data exists there:wp-discovery.js'ssampleChildEntitiesruns a live, representative check afterward — it substitutes up to 3 already-sampled parent ids into the template and fetches each, purely to say "N of 3 sampled parents actually returned something," not to claim a full count. That result surfaces as a plain-language run note, never as a channel-status change: a small sample coming back empty does not mean the capability is absent, only that this sample did not confirm it. The infrastructure is built and tested (plugin-knowledge.js,wp-route-classifier.js'schildRouteAdvertised,wp-plugin-detect.js'sdescribeProfiledEntity,wp-discovery.js'ssampleChildEntities), andplugins/woocommerce-other-payment-gateway.jsonis authored and live-verified — do not guess a plugin's installed-directory id when authoring a similar profile; confirmdetect.pluginFileIdsagainst a liveGET /wp/v2/pluginsresponse first, it is exactly the kind of fact a stale or invented guess silently gets wrong.Non-standard response envelope (
responseEnvelope, fixed 2026-08-11). Sampling and counting assume a flat array (X-WP-Total/X-WP-TotalPagesheaders, or the array's own length) or a single object. MailPoet's REST API (/mailpoet/v1/subscribers,/segments,/newsletters, ...) broke that assumption: it is a real, paginated, GET-only REST route (VERIFIED LIVE 2026-08-11: readable with the standard Application Password), but the payload is wrapped as{ data: { items: [...], meta: { count, pages } } }with noX-WP-Totalheader — the count lives inside the body instead. Before this fix the whole envelope would have sampled as one opaque record. A profile entity (route-bearing channels only) now declaresresponseEnvelope: { itemsPath, countPath }— a dot-path to the array of records, and an optional dot-path to the true total when there's no header.wp-discovery.js'sinspectEntityunwraps to that path and otherwise treats it exactly like a flat array; a path that stops resolving (stale profile, plugin version drift) falls back to the raw payload shape and records a discovery note rather than failing the run.plugins/mailpoet.jsonis authored and live-verified:crm.email-subscriptionnow resolves to migration-planned via the existingcrm/email-subscriptiontarget, withrecordCountread via the declaredcountPath. A namespace-wideunprofiledRoutesentry is still a sign a route this shape (or any other) has never been profiled — check there before concluding a plugin has "no REST surface."Route default query (
ROUTE_DEFAULT_QUERY_RULES, fixed 2026-08-16). Sampling sendsper_pageand nothing else, so any collection route that applies a default filter to an unparameterized request is read as its filtered subset and the plan under-counts — the hidden records are invisible to the mapper, not merely misreported. Observed on/wc/v3/products/reviews, which defaults tostatus=approved: a store holding both approved and on-hold reviews had only the approved ones counted. This is a class of bug, so the fix is a table rather than a special case:wp-route-classifier.jscarriesROUTE_DEFAULT_QUERY_RULES—[pattern, params, reason],*-suffix matching, longest pattern wins — anddefaultQueryFor(routePath)/defaultQueryReasonFor(routePath)resolve it.wp-discovery.jsmerges the result under its paging parameters and records a discovery note naming the parameters and the reason, so generated readers know to send them too. Adding a route is one row in the table plus a fixture; a route with no row is unchanged.
Coverage statuses
The four statuses, and only the four: migration-planned (via api or cms,
confidence confirmed or proposed), no-need-to-migrate, pending,
requires-development. A failed or unavailable read is never a status — it attaches to the
row as blocked[] (user-file / surface-changed, with a declined flag).
Checked, not guessed. A profile may declare dataPresence checks (product meta
values, post counts, shipping-class product counts, enabled shipping methods). Discovery runs them
and stores the raw results in plugin-coverage.json dataPresence (reused by
--reclassify-coverage). Every check absent → no-need-to-migrate, basis: probe,
reason: no-data-found, with the counts as the row's text. An inactive plugin whose data is
still there → no-need-to-migrate, reason: inactive-leftover (product decision: leftover data
is not moved; same as inactive redirect rules). Any unknown check (no bridge, failed or truncated
read) keeps the profile's normal path. Never report "no data" from a read you could not do.
Both no-need outcomes also need the profile's dataLocation.where to be wordpress: a plugin
that keeps data on a vendor's service (external / both) is never no-need and gets a cutover task
"Data lives in <service>" listing the profile's known options, or "options unknown: research
needed" (only a task: no blocked[] entry, no question, no stop); unknown
or a missing field keeps the normal path.
The split is deliberate: pending (we do not know how to migrate this yet — our open item)
and requires-development (a human established Wix has no surface) call for different
conversations. Only the second is a closed door, and only a human may open it — the
human-signed register plugins/requires-development.json is its single source.
Interaction rules
The admin Application Password is the source REST credential, including for
wix-wp-plugin-v2. A plugin REST namespace that honours WordPress authentication works with the Application Password, and that is the normal case — plugins with their own key systems offer them as an alternative for external callers, not a requirement (verified for Gravity Forms, which accepts Application Passwords and runs requests under the caller's plugin capabilities). Do not treat "this plugin has API keys" as "we need another credential"; that reasoning has been wrong every time it was applied. If a plugin genuinely rejects the platform credential, that is a config-gate requirement like the WooCommerce consumer keys — not a per-capability runtime state.blocked[]entries are collected and asked once, batched, each individually skippable. Auser-fileblocker means no WordPress API can reach it: unregistered post meta and plugin tables are invisible to REST, and Application Passwords cannot reachwp-admin, so absent anything else a WXR or CSV export must be produced by the user. Check the structure bridge first — ifwix-wp-plugin-v2is installed on the source site, both of those are readable through it (see "Reading key/value tables through the bridge" below), and asking the user for an export they did not need to produce is a real cost to avoid. Record each answer inorchestration/decisions.jsonunderpluginBlocker:<capability>:<kind>(provided/declined);wp-discovery.jsreads it back (--decisions, defaulting to<out-dir>/../../orchestration/decisions.json) so a declined ask renders as declined.pluginCmsFallback:<capability>sits beside it in the same file: the merchant's approve/decline answer to archiving a recognized capability's records in CMS, bound to the exact proposal shown.wp-discovery.jsreads it with the eligibility register (plugins/cms-fallback-eligible.json) and classifies the row (pendingwith acms-fallback-*reason, ormigration-planned · via cms · basis decisionwithcmsFallback.functionalityRestored: false). It is written only at the mapping review byorchestration-state.js decide-cms-fallback. A malformed entry is never honored and never fails the run; with no row to carry it, it appears inplugin-coverage.jsoncmsFallbackDecisionIssues[].plugin-coverage.jsonalso carriesentityStats(per-route record counts and sample evidence) andinputs.cmsFallbackDigest;--reclassify-coveragerebuilds coverage from them without any source request (seerp-discovery).migration-planned · proposedrows never block; the proposed capability and target are reviewed at the normal mapping-review checkpoint.requires-developmentandpendingrows must reach the user. A detected but undeliverable capability the user was never told about is the failure this machinery exists to prevent. Everypendingrow is decided at the mapping review — the only exit.
A recognized plugin always ends in Migration planned (J2 property 1). If a profile matched we know what the plugin holds, so:
no readable channel (plugin tables only) → still classified by its target, with a
user-fileblocker on the row — not pending, and never a "cannot" verdict. A database export or a source-side bridge would reach it, and automation may not foreclose that any more than it may declare Wix incapable.pending · cannot-tellis reserved for an unrecognized plugin where we genuinely found nothing; the no-migration-needed list or the agent's own reading can still resolve it to No need to migrate with a recorded rationale.The one deliberate exception is a CMS fallback: when nothing native fits, a recognized capability with a signed
cms-fallback-eligible.jsonentry stays Pending (cms-fallback-*reason) until this migration's merchant approves archiving its records in CMS. A profile never names acms/*target itself.
A CMS destination is not turnkey. "Kept as data" means the records land in a Wix CMS
collection with their original IDs — genuinely migrated, not documented. But Wix Data must be
installed first (item writes fail with WDE0110 otherwise) and collection creation has no
verified writer yet, so it is a setup step. Say both on the row; a customer reading "Kept as
data" should not discover the setup work later.
Guardrails
Never a silent native mapping. A derived entity may target a native Wix entity only when the Wix domain knowledge confirms its proposed capability; otherwise it goes to CMS. Either way the row is
confidence: proposedand is confirmed at the mapping review.Never a scope reopening. The generic path operates only on routes the route classifier already accepted. It does not resurrect frontend, editor, admin, runtime, or integration families because a plugin registered them.
Profile data routes outrank exclusion families (that is the per-capability opt-in), but a wildcard pattern must keep two concrete leading segments, so
/yoast/*can never be opted in wholesale.
Commands
node scripts/plugin-knowledge.js list-plugins
node scripts/plugin-knowledge.js read-plugin --slug the-events-calendar
node scripts/plugin-knowledge.js resolve-route --route /tribe/events/v1/events
node scripts/plugin-knowledge.js resolve-property --property bundled_items
node scripts/plugin-knowledge.js list-capabilities
node scripts/wp-plugin-inventory.js --base-url <url> --out-dir <dir> [auth options]
node scripts/plugin-knowledge-validate.js --write-indexTo add or correct a plugin, edit plugins/<slug>.json and add a fixture — no skill logic
changes. See plugins/README.md.
Product and variation stock
Extract stock_status, manage_stock, stock_quantity, backorders,
backorders_allowed, and backordered from products and every variation. Use
lib/woo-inventory.js → mapWooInventory(record, {parent}) during canonical mapping.
Persist its fields on the canonical variant and its disposition beside the source ID.
An untracked product can still be explicitly in stock; manage_stock:false is not missing
inventory. Use variation records for variable products; never replicate a parent's shared
tracked quantity onto each child. Preserve decision-needed outcomes for missing signals,
backorders, invalid quantities, and shared stock; do not turn them into an empty success.
Product bundles
WPC Product Bundles (woosb, meta woosb_ids) and WPC Composite Products (composite, meta
wooco_components) store a bundle in product meta. During canonical mapping call
lib/bundle-canonical.js → canonicalBundleFromWooProduct(record, { productsForRule }) for
every product. When hasBundleFields is true, set canonical product.bundle to its bundle, or
keep its unreadableReason; never drop either. Meta left on a product whose type is not woosb / composite
returns staleBundleMeta: true: the source sells it as a plain product, so it is not a bundle;
list those product ids in one info entry in mapping-gaps.json. Pass productsForRule to resolve a kit group
sourced from categories or tags against the extracted catalog. Keep the record's own price
unchanged (empty stays empty; never compute one from the parts). CARRIED_META_KEYS lists the
meta keys whose field decision is excluded with policyRef: "carried-to-cutover",
canonicalField: "product.bundle", carriedBy: "stores/product-bundle". What Wix does with a
bundle is the target's rule (rp-target-wix stores/product-bundle), not this adapter's.
Product videos
Product videos live in product meta written by a plugin or the theme, not in images[].
product-video-sources.json lists the meta keys (TheGem thegem_product_video, Product Video
Gallery _nickx_video_text_url, ...); add a source there, not in code. After the product extract,
run node scripts/product-videos.js plan --project <dir>. It writes execution/product-videos.json:
attach[] (video files, attached by the importer, see rp-import-codegen "Product videos") and
manual[] (YouTube/Vimeo/other links: the completion report turns them into the
product-video-manual Cutover Operator item). Never put a video URL in the product's image list.
Read contract (codegen-time)
What a generated WordPress reader must get right. Capture the operational facts below into
source-profile.md during discovery so codegen has them without re-deriving.
The generated reader is an extractor, not an in-memory bulk loader. It should fetch WordPress/WooCommerce records page by page and write them to project-local files (for example per-entity paged JSON files plus a manifest) so the import step can read from disk later without re-fetching the source.
Reuse the shared transport — do not regenerate it. The auth, URL building, rate-limit
throttling, and Retry-After-aware 429/503 backoff a reader needs already exist as a
dependency-free module at lib/wp-http.js in this skill directory (the same module
the capture script imports). It
exports fetchJson, buildHeaders, configureRateLimit, and parseTotalHeader. It does
not export an undenied transport — fetchJson refuses payment-gateway routes, and a
generated reader must not reintroduce a raw one. Any
generated WordPress reader must reuse this module rather than reimplementing transport,
so the reader contains only per-project orchestration: which entities to pull, the
pagination loop, _embed/_links resolution, and transform glue. One tested transport
core is what makes the sampler and the reader behave identically. How the module is
carried into a runnable migration project is rp-import-codegen's concern (its File
targets), not this adapter's. The notes below describe what the reader does on top of
that shared core:
Bounded media reads:
fetchJsonaccepts optionaldeadlineMs. One absolute deadline includes the rate-limit wait, every fetch attempt, each attempt timeout, response handling, and every retry delay. A wait that would finish after the deadline is not started. OmitdeadlineMsfor all existing calls; their behavior stays unchanged.Namespaces & auth differ per namespace:
wp/v2(core): HTTP Basic auth with a WordPress Application Password (--username+--application-password).wc/v3(WooCommerce): consumer key / secret, sent as Basic auth over HTTPS (or as query params on some hosts). This is a different credential from the Application Password — both may be needed for a full migration.
Pagination:
?page=N&per_page=M(maxper_pageis typically 100). Total pages are in theX-WP-TotalPagesresponse header and total records inX-WP-Total— read those rather than guessing when to stop. Some public WooCommerce Store API collection routes paginate withoutX-WP-TotalPages; when that header is absent, generated readers must stop on the first page whose item count is smaller thanper_page.Embedded relations: request
?_embedto inline related resources, or follow the_linksblock (author,wp:featuredmedia,wp:term) to resolve relations. Theevidencepointers insource-schema.jsonrelations come from this_linksblock.Hierarchical taxonomies: WordPress categories (and custom hierarchical taxonomies) carry a
parentfield on each term (0= top-level). When any term has a non-zeroparent, the source taxonomy is nested. Discovery must elevate this into structured schema — set"hierarchical": trueon that entity insource-schema.json(seesource-schema.example.json→category) rather than leavingparentburied in the raw dump. The Wix Blog category target is flat (no parent/child), so this flag is what triggers the mapper's mandatory lossiness entry; without it, the flatten happens silently.Rate limits / retries: not advertised; the capture script throttles (
--rate-limit-rpm, default 120) and backs off on 429/503 honoringRetry-After. Generated readers should inherit the same discipline.Rich content:
content.rendered/title.renderedare HTML;*.rawrequirescontext=edit(authenticated). Note which the reader should pull.HTML entities in "plain text" fields (trap, hit live 2026-07-19): WordPress returns HTML-encoded entities (
–,&,’, …) not only in rendered HTML but also in fields consumed as plain text — product/category/tagname,title.renderedafter tag-stripping, excerpts, even SKUs. Values sent to plain-text Wix fields (product name, blog title, tag label, CMS text columns) must be entity-decoded by the generated transforms or the encoded form appears verbatim in the Wix dashboard. HTML passed to rich-content conversion does NOT need pre-decoding — the converter handles entities.slug/post_nameis percent-encoded for non-Latin values, and REST returns it undecoded (trap, confirmed live on a non-Latin source 2026-09-27): WordPress stores a post/product slug whose original text contains non-Latin characters (e.g. Hebrew) as raw UTF-8 percent-encoded escapes (%d7%90%d7%99...), and bothwp/v2andwc/v3return this field exactly as stored — no decoding happens server-side. The target's slug coercion (rp-target-wix'stoWixSlug) turns the literal%characters into dashes rather than erroring, so passing this value straight through silently produces a garbled hex-with-dashes URL instead of the real slug. Generated transforms must decodeslug/post_namewithdecodeURIComponentbefore using it as a Wix slug or any other field — guarded in a try/catch, since a slug that was never percent-encoded (or one containing a literal%that isn't part of a valid escape) must pass through unchanged rather than throw or get mangled. The decoded Unicode slug is then kept as-is (the coercion preserves letters and digits in any script), so do not transliterate it. See the codegen-side rule inrp-import-codegen/SKILL.md's "Never hand-write slug sanitizing" section and the domain-knowledge pitfalls onrp-target-wix'sstores/entities/product.jsonandblog/entities/post.json.Custom fields: ACF / meta often appear in sample records but are absent from the
OPTIONSschema — surface them asunknownsin discovery so the mapper can decide.WooCommerce variation attribute values are URL-encoded slugs, not display names (trap, hit live 2026-07-21):
variations[].attributes[].valuefromwc/v3/products/{id}/variationsis a URL-encoded taxonomy-term slug (e.g.caf%c3%a9forcafé), not the human-readable display name that the product'sattributes[].options[]array contains. Generated readers must build a per-option slug→displayName map from the parent product'sattributes[].options[](which does carry display names) and resolve slug values to display names before writing to Wix. Passing slugs directly causesMISSING_VARIANT_OPTION_CHOICEbecause Wix compares variant choice names against option choice names and finds no match.WooCommerce "Any"-style variations omit the attribute entirely, and fail silently (trap, hit live 2026-07-21):
wc/v3returns the per-variation field asattributes[].option, not.value. When a WooCommerce variation is set to "Any" for an option (the variation applies to any value of that option), that attribute is typically omitted from the variation'sattributesarray entirely rather than present with a null/emptyoption— but treat a present-and-emptyoptionthe same way if seen. Generated transforms that require every declared parent attribute to appear on the variation will resolve an empty option set for it. This does not fail loudly — Wix accepts the write — it surfaces only as a product that goes live with zero purchasable options, found by a human browsing the storefront, not by any automated check. Do not "fix" this by auto-expanding into a cartesian combination of all option choices: live-refuted (the combination count explodes for some products, because the attribute slots are ordinal pick-N-from-a-shared-list pickers, not independent size/color axes). The correct handling is to record the loss for human review rather than emit a default variant silently.The store's own configuration must be read DIRECTLY, and with the WordPress credential (trap, hit live 2026-09-01):
/wc/v3/settings/generalholds the business address (woocommerce_store_address,_address_2,_city,_postcode,woocommerce_default_country), the currency, which countries the shop sells to, and whether tax is calculated. Two reasons it was never captured on any run:The REST index advertises only the parameterized form
/wc/v3/settings/(?P<group>...), never the literal group route, so nothing in the generic sweep ever fetches it. Read/wc/v3/settings/generaldirectly, the same way a shipping zone's/locationsand/methodssub-resources are — a parent-scoped sub-resource the caller resolves itself.The WooCommerce consumer key gets
401 woocommerce_rest_cannot_viewhere; the WordPress application password gets200. Both are already in every run's source config. A reader that only tries the store key gets a plausible "no permission" and moves on — which is exactly how this stayed invisible while migrated sites published with an empty business address.
woocommerce_default_countryisCOUNTRYorCOUNTRY:STATE(e.g.US:CA) — the same packing a zone'sstate-type location uses.rp-target-wix/lib/store-config-build.jsmaps the whole group; do not hand-roll it.Route paths passed to
fetchJson/buildApiUrlmust NOT include/wp-json(trap, hit live 2026-07-21):buildApiUrlinlib/wp-http.jsalready prepends/wp-jsonto theroutePathargument. Generated route paths must start with the namespace directly (e.g./wc/store/v1/products,/wp/v2/posts) — never with/wp-json/.... Prefixing with/wp-jsondoubles the prefix and produces 404s.WooCommerce consumer key/secret can 401 on some
wc/v3routes even when it reads others fine (trap, hit live 2026-08-12):WC_CONSUMER_KEY/WC_CONSUMER_SECRETare scoped at key-creation time (Read / Write / Read-Write) and can be narrower than the WordPress Application Password's access. The consumer key/secret can 401woocommerce_rest_cannot_viewonwc/v3/taxes,wc/v3/taxes/classes, andwc/v3/settings/taxwhile the very same reads succeeded immediately with theWP_USERNAME/WP_APPLICATION_PASSWORDBasic auth pair. Generated readers must not treat a 401/403 on onewc/v3route as proof the whole consumer key is broken (which would wrongly block products/orders/coupons too) — retry that specific route with the Application Password credential before failing, and prefer the Application Password outright for admin-ishwc/v3routes (taxes, settings) that a narrowly-scoped key is more likely to be denied on.Core WooCommerce settings/tax routes are core, not plugin data:
wc/v3/taxes,wc/v3/taxes/classes, andwc/v3/settings/taxare ordinary WooCommerce core collections (same auth/pagination rules aswc/v3/productsetc.) — they are not profiled as a "plugin" because tax is core WooCommerce, not an extension. Per-producttax_status/tax_classfields ride along on the ordinarywc/v3/productsread; no separate per-product route is needed to get them. Seerp-target-wixdomains/tax/ for the corresponding Wix target entities (Tax Group / Tax Region / Manual Tax Mapping / Tax Settings) and mapping-plan.json'sproductandtax-classentities.
Schema shape
source-schema.example.json (in this skill folder) is the template rp-discovery follows
when emitting migrations/<project>/source-schema.json. It is a shape to follow, not a
strict schema to validate against. Keep the platform-agnostic core stable; push WordPress
quirks (restNamespace, statuses, etc.) into each entity's open sourceMeta blob.
For a profiled plugin entity, sourceMeta MUST also carry requestMethod, requestBody,
and responseFragmentGroupSize verbatim whenever the plugin profile declares them — copy them from the profile entity (surfaced structurally in plugin detection's
per-entity output, wp-plugin-detect.js's describeProfiledEntity) rather than re-deriving
them from discovery's prose notes. rp-import-codegen's read contract depends on finding
these under exactly those sourceMeta keys; omitting them silently degrades a declared
non-GET/fragmented read into an unreadable one downstream.
WooCommerce/WordPress meta_data[] is a keyed list ({id, key, value}). Record it for
mapping as one dynamic coverage entry, {path: "meta_data[].value", dynamic: true, selector: {keyPath: "meta_data[].key"}, observedKeys: [...]}, never as a blanket claim.
The read-back inventory then counts each key separately (meta_data[key="_yoast_wpseo_title"].value)
and lists nested plugin values below it. Keys such as @type, @graph, Hebrew labels or
percent-encoded attribute slugs are kept exactly, quoted per lib/source-location.js
(yoast_head_json.schema["@graph"][]["@type"]); never strip, rename or decode them.
Coupons, coupon usage and the currency gate
Three source-side decisions, each in a library so a generated importer supplies facts rather than
rules. Read lib/coupon-discovery.js and lib/currency-gate.js; both are pure.
Coupons are counted from one surface and imported from the same one.
wc/v3/coupons(published) is the discovered set and the denominator; sweep it to exhaustion withsweepCoupons(fetchPage), which refuses a total that disagrees withX-WP-Total. Thepostscount bypost_statusis a reconciliation check only —summarizeCoupons({ restCoupons, postsByStatus })reports the non-published rows as deliberately excluded, never as a shortfall (the difference being drafts and auto-drafts).Redeemability, not expiry, classifies a coupon.
classifyCoupon— redeemable iff not expired and not usage-exhausted;usage_limit0 or empty means UNLIMITED. Ausage_limitorusage_countthat is not an integer ("1.5","abc") isunresolved: neither redeemable nor exhausted, not written (coupon-usage-limit-unresolved), its own partition line. Import all published coupons; the report carries the breakdown, never "imported N coupons".Mapping reports rather than approximates.
mapCouponToWix(coupon, { resolveProduct, resolveCategory })returns a Wix specification or a named refusal:fgf_free_giftand any unknowndiscount_typearecoupon-type-unmappable, and so is an unrestrictedfixed_product(a per-unit amount on every product; Wix's money-off takes it off the order once — a product-scoped one maps); a scope Wix cannot hold in one group iscoupon-scope-unmappable. An exhausted single-use code is importedactive: false, because Wix's usage count starts at zero. An eligibility constraint Wix cannot hold — excluded products or categories, a sale-item exclusion, a maximum discount amount, an email restriction, or a minimum spend on a product/collection-scoped coupon — is a refusal (coupon-scope-unmappable, reasonscope: constraints): dropped, each would make the coupon more generous than the merchant published. Only a dropped amount on a free-shipping coupon stays a per-coupon finding.Coupon plugins' rules are profile data. A coupon plugin (Smart Coupons, …) stores extra rules as coupon meta. Its profile's
couponRules[]names each key's meaning, andmapCouponToWixacts on it:start-datesetsstartTime;same-as-coreandno-effectchange nothing;restriction/gift/auto-applywrite the coupon switched off, taggedRule_Not_Carried, withresult.holdand onecoupon-plugin-rule-heldcutover task (couponOperatorActions). Coupon meta no profile names is reported once per key (coupon-meta-unrecognizedinsummarizeCoupons); the coupon still maps. To support a new coupon plugin, addcouponRules[]to its profile — never code here.Coupon usage rides on the order. On legacy post storage the surface is the order's REST
coupon_lines[](each carryingdiscountper code); HPOS stores havewc_order_coupon_lookup. Name whichever was found ascoupon-usage-surface. The target side (rp-target-wix/lib/order-applied-discount-build.js) turns the lines intoappliedDiscountsthrough the coupon crosswalk; an unresolved code writes nothing and is reported.Currency halts before any order write.
currency-gate.jsevaluateCurrencyGate({ settingsCurrency, orderCurrencies, targetSiteCurrency })— settings fromwc/v3/settings/generalthroughstore-currency.js, order currencies throughresolveOrderCurrency(which decodes₪and refuses a contradicting symbol). One currency matching the site proceeds withcurrency-validated; a mismatch or a history spanning two currencies is a halt, and unresolved orders halt too. Two configured currencies with a single-currency history proceeds, with the configuration reported.Plan-shaped sources are gated by row counts (
B1subscription products,B2membership CPT,B3recurring-plan meta), never by plugin detection. Zero rows on all three reports "no pricing plans found". The gate and the plan body live target-side inrp-target-wix/lib/pricing-plan-definition.js.
Currency is a store setting, not an order field
order.currency is documented as an ISO 4217 code. Do not trust it. A store can return
currency: "₪" (an HTML-encoded currency SYMBOL) on every order, because a plugin or
theme filter has overridden the field. Passed through, the payment
existence gate refuses every payment as a currency mismatch; passed through without a gate it
labels amounts with a symbol.
lib/store-currency.js resolves it: readStoreCurrency() reads woocommerce_currency from
/wc/v3/settings/general (one request per run, and the store's own authoritative setting), and
resolveOrderCurrency(order, storeCurrency) trusts the order's own value when it is a plausible
ISO code — a multi-currency store legitimately holds several — and falls back to the store setting
when it is not. It reports order-currency-not-iso when it falls back, because a store that
mangles this field is a store whose other currency-bearing fields are suspect too.
It never infers a code from a symbol. $ is at least a dozen different currencies, and guessing
one silently mislabels money.
Site locale facts: source-locale.json
Discovery also writes data/wp-discovery/source-locale.json (promotion copies it to
discovery/source-locale.json; a missing or invalid file refuses promotion). It records the
store's currency, time zone, language and country through lib/regional-capture.js, which maps
the settings JSON onto buildSourceRegional:
| Neutral field | WordPress / WooCommerce source | Rule |
|---|---|---|
paymentCurrency | woocommerce_currency from wc/v3/settings/general (readStoreCurrency; the data/store-settings-general.json capture is reused) | never read from an order |
timeZone | wp/v2/settings timezone (timezone_string) | a site on a fixed gmt_offset has no zone: unknown / not-exposed, never an offset |
language, locale | wp/v2/settings language tag plus woocommerce_default_country | he_IL → language he, locale he-IL; otherwise the country part before the colon supplies the region |
Per-order currency counts remain WooCommerce adapter evidence and do not enter the neutral locale record.
A denied read (401/403) is auth-gated, a missing route (404) not-exposed, any other failure
unreadable; none of them fails discovery. wp/v2/settings needs an administrator credential, so
a run without one records language and time zone as auth-gated. The field names come from the
WordPress and WooCommerce REST schemas; the first run against a store confirms them.
Files
- ATTRIBUTION.mdAdded by AutoGineer850 B
- LICENSELicence file added by AutoGineer1.0 KiB
- PLUGIN-READ-PLANS.md13.2 KiB
- SKILL.md71.7 KiB
- archive-fields.v1.json2.4 KiB
- lib/applied-offer-summary.jsScript6.2 KiB
- lib/blocked-data-handlers.jsScript3.7 KiB
- lib/bundle-canonical.jsScript8.0 KiB
- lib/checkout-field-csv-parser.jsScript4.9 KiB
- lib/checkout-field-csv-parser.test-fixture.jsScript5.0 KiB
- lib/coupon-discovery.jsScript40.7 KiB
- lib/currency-gate.jsScript5.9 KiB
- lib/gateway-source-keys.jsScript11.9 KiB
- lib/gateway-source-keys.json7.0 KiB
- lib/gateway-summary.mjsScript14.3 KiB
- lib/invoice-discovery.jsScript20.8 KiB
- lib/plugin-data-presence.jsScript20.6 KiB
- lib/plugin-disposition.jsScript19.4 KiB
- lib/plugin-entity-read-plan.jsScript56.3 KiB
- lib/plugin-knowledge.jsScript66.7 KiB
- lib/product-video-extract.jsScript4.9 KiB
- lib/refund-corroboration.jsScript8.0 KiB
- lib/refund-corroboration.json4.1 KiB
- lib/regional-capture.jsScript7.9 KiB
- lib/sampled-ids-batch.jsScript7.0 KiB
- lib/secret-value-guard.jsScript10.5 KiB
- lib/store-currency.jsScript4.9 KiB
- lib/structure-bridge-reader.jsScript39.9 KiB
- lib/wix-wp-plugin-v2-client.jsScript46.9 KiB
- lib/wix-wp-plugin-v2-client.test-fixture.jsScript6.7 KiB
- lib/woo-inventory.jsScript2.0 KiB
- lib/woo-selection-attributes.jsScript4.5 KiB
- lib/wp-http.jsScript16.8 KiB
- lib/wp-image-url.jsScript8.6 KiB
- lib/wp-plugin-detect.jsScript86.2 KiB
- lib/wp-redirect-sources.jsScript23.6 KiB
- lib/wp-route-classifier.jsScript30.2 KiB
- lib/yoast-product-seo-evidence.jsScript12.9 KiB
- plugins/README.md30.1 KiB
- plugins/advanced-custom-fields.json9.6 KiB
- plugins/advanced-product-labels-for-woocommerce.json1.6 KiB
- plugins/back-in-stock-notifier-for-woocommerce.json5.9 KiB
- plugins/capabilities-pending-decision.json24.8 KiB
- plugins/cms-fallback-eligible.json2.4 KiB
- plugins/contact-form-7.json9.2 KiB
- plugins/cutover-task-only.json17.7 KiB
- plugins/facebook-for-woocommerce.json2.1 KiB
- plugins/fingerprint-aliases.json4.5 KiB
- plugins/forminator.json7.9 KiB
- plugins/free-gifts-for-woocommerce.json8.9 KiB
- plugins/index.json27.8 KiB
- plugins/mailpoet.json2.4 KiB
- plugins/membership-for-woocommerce.json20.8 KiB
- plugins/min-and-max-quantity-for-woocommerce.json1.7 KiB
- plugins/mwb-bookings-for-woocommerce.json20.3 KiB
- plugins/no-migration-needed.json17.2 KiB
- plugins/pricing-deals-for-woocommerce.json7.0 KiB
- plugins/product-extras-for-woocommerce.json9.0 KiB
- plugins/product-video-gallery-slider-for-woocommerce.json2.2 KiB
- plugins/pw-woocommerce-gift-cards.json12.1 KiB
- plugins/redirection.json2.7 KiB
- plugins/requires-development.json10.2 KiB
- plugins/seo-by-rank-math.json9.0 KiB
- plugins/seriously-simple-podcasting.json1.9 KiB
- plugins/strong-testimonials.json3.4 KiB
- plugins/subscriptions-for-woocommerce.json8.5 KiB
- plugins/tablepress.json3.0 KiB
- plugins/the-events-calendar.json6.7 KiB
- plugins/ti-woocommerce-wishlist.json4.0 KiB
- plugins/wc-coupon-discount-to-specific-products.json1.9 KiB
- plugins/wm-cart-upsell.json2.8 KiB
- plugins/woo-checkout-field-editor-pro.json4.6 KiB
- plugins/woo-discount-rules.json5.6 KiB
- plugins/woo-free-shipping-per-product.json2.2 KiB
- plugins/woo-product-bundle.json6.6 KiB
- plugins/woocommerce-gift-cards.json2.1 KiB
- plugins/woocommerce-other-payment-gateway.json2.6 KiB
- plugins/woocommerce-pdf-invoices-packing-slips.json2.9 KiB
- plugins/woocommerce-product-addon.json10.2 KiB
- plugins/woocommerce-progressive-discounts.json4.8 KiB
- plugins/wordpress-seo-premium.json1.6 KiB
- plugins/wordpress-seo.json15.2 KiB
- plugins/wpc-composite-products.json12.2 KiB
- plugins/wpforms-lite.json7.1 KiB
- plugins/wt-smart-coupons-for-woocommerce.json4.9 KiB
- product-video-sources.json1.2 KiB
- scripts/capture-store-settings.jsScript4.0 KiB
- scripts/plugin-full-read.jsScript3.6 KiB
- scripts/plugin-knowledge-validate.jsScript1.7 KiB
- scripts/plugin-knowledge.jsScript3.8 KiB
- scripts/product-videos.jsScript1.9 KiB
- scripts/wp-discovery.jsScript124.2 KiB
- scripts/wp-plugin-inventory.jsScript10.7 KiB
- secret-value-patterns.v1.json537 B
- source-schema.example.json3.2 KiB
- sub-parts.json733 B
scripts/wp-discovery.js
#!/usr/bin/env node
const fs = require('node:fs/promises');
const path = require('node:path');
const { createProgressLogger, parseProgressArgs } = require('../../../lib/progress-log.js');
const { readEnvFile } = require('../../../lib/config-env.js');
const { buildWordPressCoverageRows, buildCoverageFile, ADAPTER_RAW_DIRS } = require('../../../lib/source-coverage.js');
const { writeAdapterSourceRegional } = require('../../../lib/source-regional.js');
const regionalCapture = require('../lib/regional-capture.js');
// Transport, auth, throttling, and pagination-header parsing live in the shared
// adapter lib so the bulk-extract reader generated by rp-import-codegen inherits
// the exact same discipline instead of re-deriving it.
const {
DEFAULT_TIMEOUT_MS,
DEFAULT_RATE_LIMIT_RPM,
DEFAULT_MAX_RETRIES,
configureRateLimit,
buildHeaders,
normalizeBaseUrl,
fetchJson,
parseTotalHeader,
} = require('../lib/wp-http.js');
const {
classifyRoutes,
summarizeSkippedByCategory,
buildRegisteredRestBases,
defaultPluginRules,
defaultQueryFor,
defaultQueryReasonFor,
} = require('../lib/wp-route-classifier.js');
// Plugin awareness: detection runs before classification so profile routes are
// in scope; embedded detection and Tier-B derivation run after sampling because they need
// real record payloads and the accepted route set.
const { gatherInventory, inventoryPayload } = require('./wp-plugin-inventory.js');
// discover-structure/query-structure: the only source for entities whose
// blocked[].fulfillment.kind is structure-bridge-plugin -- data with no REST route at all.
const {
discoverStructure, queryStructure, guardedValueColumns, violatesTierRule,
discoverEavKeys, buildEavReadPlan, MAX_PAGE_LIMIT,
} = require('../lib/wix-wp-plugin-v2-client.js');
const redirectSources = require('../lib/wp-redirect-sources.js');
const {
pluginsRoot,
loadProfiles,
loadNoMigrationNeeded,
loadRequiresDevelopment,
loadPendingDecisions,
loadFingerprintAliases,
loadCutoverTasks,
loadCmsFallbackEligible,
CHILD_ROUTE_PLACEHOLDER,
buildResponseEnvelopes,
buildRequestOverrides,
buildResponseFragmentGroups,
buildRecordKeyFields,
} = require('../lib/plugin-knowledge.js');
const {
buildDispositionRows,
summarizeDispositions,
} = require('../lib/plugin-disposition.js');
const {
cmsFallbackDecisionKeys,
cmsFallbackDecisionShape,
capabilityOfKey: cmsFallbackCapabilityOfKey,
cmsFallbackResolutionInputs,
cmsFallbackInputsDigest,
detectedPluginsOf,
} = require('../../../lib/plugin-cms-fallback.js');
const {
detectPlugins,
describeProfiledEntity,
collectRecordProperties,
collectUnprofiledRoutes,
collectCandidateNamespaces,
deriveGenericEntities,
deriveBridgePlannedEntities,
classifyCoverage,
coverageSummary,
registerKeys,
} = require('../lib/wp-plugin-detect.js');
const { collectPresenceObservations, presenceByPlugin } = require('../lib/plugin-data-presence.js');
const {
collectAllIds,
queryInBatches,
DEFAULT_BATCH_SIZE,
} = require('../lib/sampled-ids-batch.js');
const DEFAULT_SAMPLE_LIMIT = 3;
let progress;
function printUsage() {
console.log(`Usage:
node wp-discovery.js --base-url <url> --out-dir <dir> [auth options]
Required:
--base-url <url> WordPress site base URL, e.g. https://example.com
--out-dir <dir> Directory to write discovery markdown files into
--decisions <path> orchestration/decisions.json to read batched-ask answers from
(default: <out-dir>/../../orchestration/decisions.json)
--env-file <path> Load defaults from a project-local env file
Reclassify without refetching (no source network calls):
node wp-discovery.js --reclassify-coverage --out-dir <dir> [--decisions <path>]
[--canonical-coverage <path>]
Rebuilds <out-dir>/plugin-coverage.json from the stored plugin-inventory.json, the prior
coverage's entityStats/review evidence, and the current profiles, registers, target
knowledge and decisions. Also rewrites --canonical-coverage (default:
<out-dir>/../../discovery/plugin-coverage.json when that directory exists). Exits 3 with
outcome needs-full-discovery, writing nothing, when the stored evidence is incomplete.
Authentication options:
--username <name> WordPress username for Application Password auth
--application-password <pw> WordPress Application Password
--api-key <token> API key/token for custom auth setups
--api-key-header <name> Header name for --api-key. Defaults to Authorization
--auth-header <'Name: Value'> Add a raw HTTP header. Can be repeated.
Optional:
--sample-limit <n> Number of sample records per entity. Default: 3
--timeout-ms <n> Request timeout in ms. Default: 60000
--rate-limit-rpm <n> Max requests per minute. Default: 120
--max-retries <n> Retries on 429/503 (honors Retry-After). Default: 3
--commerce-mode <mode> WooCommerce read mode: public | authenticated.
Defaults to public without auth, otherwise authenticated.
--no-plugin-inventory Skip plugin detection, Tier-B derivation, and coverage.
--no-html-fingerprint Skip the homepage fetch used for asset-path fingerprints.
--include-namespace <ns> Only inspect a namespace. Can be repeated.
--include-route <path> Force-sample a route. Can be repeated.
--include-excluded-category <category>
Force-sample an excluded category. Can be repeated.
--exclude-route <path> Skip a route even if otherwise sampled. Can be repeated.
--override-reason <text> Reason recorded for include/exclude overrides.
--progress-log <path> Append progress NDJSON records to this file.
--help Show this help text
Examples:
node wp-discovery.js \
--base-url https://example.com \
--out-dir migrations/acme/data/wp-discovery \
--username admin \
--application-password 'abcd efgh ijkl mnop'
node wp-discovery.js \
--base-url https://example.com \
--out-dir migrations/acme/data/wp-discovery \
--api-key $WP_API_KEY \
--api-key-header X-API-Key
`);
}
function parseArgs(argv) {
const args = {
authHeaders: [],
includeNamespaces: [],
includeRoutes: [],
includeExcludedCategories: [],
excludeRoutes: [],
overrideReason: null,
sampleLimit: DEFAULT_SAMPLE_LIMIT,
timeoutMs: DEFAULT_TIMEOUT_MS,
rateLimitRpm: DEFAULT_RATE_LIMIT_RPM,
maxRetries: DEFAULT_MAX_RETRIES,
commerceMode: null,
pluginInventory: true,
htmlFingerprint: true,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
const next = argv[i + 1];
switch (arg) {
case '--help':
case '-h':
args.help = true;
break;
case '--base-url':
args.baseUrl = next;
i += 1;
break;
case '--out-dir':
args.outDir = next;
i += 1;
break;
case '--decisions':
args.decisions = next;
i += 1;
break;
case '--env-file':
args.envFile = next;
i += 1;
break;
case '--username':
args.username = next;
i += 1;
break;
case '--application-password':
args.applicationPassword = next;
i += 1;
break;
case '--api-key':
args.apiKey = next;
i += 1;
break;
case '--api-key-header':
args.apiKeyHeader = next;
i += 1;
break;
case '--auth-header':
args.authHeaders.push(next);
i += 1;
break;
case '--sample-limit':
args.sampleLimit = Number.parseInt(next, 10);
i += 1;
break;
case '--timeout-ms':
args.timeoutMs = Number.parseInt(next, 10);
i += 1;
break;
case '--rate-limit-rpm':
args.rateLimitRpm = Number.parseInt(next, 10);
i += 1;
break;
case '--max-retries':
args.maxRetries = Number.parseInt(next, 10);
i += 1;
break;
case '--commerce-mode':
args.commerceMode = next;
i += 1;
break;
case '--include-namespace':
args.includeNamespaces.push(next);
i += 1;
break;
case '--include-route':
args.includeRoutes.push(next);
i += 1;
break;
case '--include-excluded-category':
args.includeExcludedCategories.push(next);
i += 1;
break;
case '--exclude-route':
args.excludeRoutes.push(next);
i += 1;
break;
case '--override-reason':
args.overrideReason = next;
i += 1;
break;
case '--no-plugin-inventory':
args.pluginInventory = false;
break;
case '--no-html-fingerprint':
args.htmlFingerprint = false;
break;
case '--reclassify-coverage':
args.reclassifyCoverage = true;
break;
case '--canonical-coverage':
args.canonicalCoverage = next;
i += 1;
break;
// Fixture-tree overrides for tests; both default to the installed skill.
case '--plugins-root':
args.pluginsRoot = next;
i += 1;
break;
case '--target-knowledge-root':
args.targetKnowledgeRoot = next;
i += 1;
break;
default:
if (arg.startsWith('--')) {
throw new Error(`Unknown argument: ${arg}`);
}
}
}
if (!args.baseUrl) {
args.baseUrl = process.env.WP_BASE_URL || process.env.WP_SITE_URL;
}
if (!args.outDir) {
args.outDir = process.env.WP_DISCOVERY_OUT_DIR;
}
if (!args.apiKey) {
args.apiKey = process.env.WP_API_KEY;
}
if (!args.apiKeyHeader) {
args.apiKeyHeader = process.env.WP_API_KEY_HEADER;
}
if (!args.username) {
args.username = process.env.WP_USERNAME;
}
if (!args.applicationPassword) {
args.applicationPassword = process.env.WP_APPLICATION_PASSWORD;
}
if (args.authHeaders.length === 0 && process.env.WP_AUTH_HEADER) {
args.authHeaders.push(process.env.WP_AUTH_HEADER);
}
if (!Number.isFinite(args.sampleLimit) || args.sampleLimit < 1) {
args.sampleLimit = DEFAULT_SAMPLE_LIMIT;
}
if (!Number.isFinite(args.timeoutMs) || args.timeoutMs < 1000) {
args.timeoutMs = DEFAULT_TIMEOUT_MS;
}
if (!Number.isFinite(args.rateLimitRpm) || args.rateLimitRpm < 1) {
args.rateLimitRpm = DEFAULT_RATE_LIMIT_RPM;
}
if (!Number.isFinite(args.maxRetries) || args.maxRetries < 0) {
args.maxRetries = DEFAULT_MAX_RETRIES;
}
if (args.commerceMode !== 'public' && args.commerceMode !== 'authenticated') {
args.commerceMode = (args.username && args.applicationPassword) || args.apiKey || args.authHeaders.length > 0
? 'authenticated'
: 'public';
}
return args;
}
async function hydrateArgsFromEnvFile(args) {
if (!args.envFile) {
return args;
}
const envValues = await readEnvFile(path.resolve(args.envFile));
if (!args.baseUrl && envValues.WP_BASE_URL) {
args.baseUrl = envValues.WP_BASE_URL;
}
if (!args.username && envValues.WP_USERNAME) {
args.username = envValues.WP_USERNAME;
}
if (!args.applicationPassword && envValues.WP_APPLICATION_PASSWORD) {
args.applicationPassword = envValues.WP_APPLICATION_PASSWORD;
}
if (!args.apiKey && envValues.WP_API_KEY) {
args.apiKey = envValues.WP_API_KEY;
}
if (!args.apiKeyHeader && envValues.WP_API_KEY_HEADER) {
args.apiKeyHeader = envValues.WP_API_KEY_HEADER;
}
if (args.authHeaders.length === 0 && envValues.WP_AUTH_HEADER) {
args.authHeaders.push(envValues.WP_AUTH_HEADER);
}
return args;
}
function endpointMethods(endpoint) {
const raw = endpoint?.methods;
if (Array.isArray(raw)) {
return raw.map(String);
}
if (typeof raw === 'string') {
return raw.split(',').map((value) => value.trim()).filter(Boolean);
}
if (raw && typeof raw === 'object') {
return Object.keys(raw);
}
return [];
}
function routeSegments(routePath) {
return routePath.split('/').filter(Boolean);
}
function summarizeRelationships(record) {
const links = record?._links;
if (!links || typeof links !== 'object') {
return [];
}
// HAL housekeeping rels carry no entity relationship signal.
const ignored = new Set(['self', 'collection', 'about', 'curies']);
const relationships = [];
for (const [rel, entries] of Object.entries(links)) {
if (ignored.has(rel)) {
continue;
}
const list = Array.isArray(entries) ? entries : [entries];
const hrefs = list.map((entry) => entry?.href).filter(Boolean);
if (hrefs.length === 0) {
continue;
}
relationships.push({
rel,
embeddable: list.some((entry) => entry?.embeddable === true),
hrefs,
});
}
return relationships;
}
function isParameterizedRoute(routePath) {
return routePath.includes('(?P<');
}
function slugify(value) {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '') || 'entity';
}
function summarizeAuthMode(args) {
if (args.username && args.applicationPassword) {
return 'basic-application-password';
}
if (args.apiKey) {
return `api-key:${args.apiKeyHeader || 'Authorization'}`;
}
if (args.authHeaders.length > 0) {
return 'custom-header';
}
return 'none';
}
// wix-wp-plugin-v2 0.5.0+ admits `manage_woocommerce` or `manage_options`, so
// one WordPress REST credential reaches the bridge with or without WooCommerce. There is no
// other bridge credential.
function summarizeBridgeAuthMode(args) {
const hasRestCredential = Boolean(
(args.username && args.applicationPassword) || args.apiKey || args.authHeaders.length > 0,
);
return hasRestCredential ? 'wordpress-rest-credential' : 'none';
}
// A 403 from the bridge on a site without WooCommerce means a plugin copy older than 0.5.0,
// whose routes required `manage_woocommerce` (a capability that exists only with
// WooCommerce). The fix is updating the plugin, not a different credential.
const BRIDGE_PLUGIN_UPDATE_REQUIRED = 'bridge_plugin_update_required';
function bridgeForbiddenCode(status, namespaces) {
if (status !== 403) return null; // 401 is a missing/invalid credential, not an old plugin
return (namespaces || []).some((namespace) => namespace.startsWith('wc/')) ? null : BRIDGE_PLUGIN_UPDATE_REQUIRED;
}
function summarizeOverrides(args) {
return {
includeRoutes: args.includeRoutes,
includeNamespaces: args.includeNamespaces,
includeExcludedCategories: args.includeExcludedCategories,
excludeRoutes: args.excludeRoutes,
overrideReason: args.overrideReason,
commerceMode: args.commerceMode,
};
}
function deriveEntityCandidates(indexJson, includeNamespaces, requestOverrides = new Map()) {
const routes = indexJson?.routes || {};
const candidates = [];
for (const [routePath, routeDefinition] of Object.entries(routes)) {
if (!routePath.startsWith('/') || routePath === '/' || isParameterizedRoute(routePath)) {
continue;
}
const segments = routeSegments(routePath);
if (segments.length < 2) {
continue;
}
const namespace = segments.slice(0, 2).join('/');
if (includeNamespaces.length > 0 && !includeNamespaces.includes(namespace)) {
continue;
}
const endpoints = Array.isArray(routeDefinition?.endpoints) ? routeDefinition.endpoints : [];
// A profile may declare that this entity's real read path is not GET (see
// plugin-knowledge.js buildRequestOverrides) — the declared method then stands in for
// the GET-collection requirement below, generically for any plugin/entity.
const requestOverride = requestOverrides.get(routePath) || null;
const getEndpoint = requestOverride
? endpoints.find((endpoint) => endpointMethods(endpoint).includes(requestOverride.method))
: endpoints.find((endpoint) => endpointMethods(endpoint).includes('GET'));
if (!getEndpoint) {
continue;
}
const entityName = segments[segments.length - 1];
const supportsPagination = Boolean(getEndpoint?.args?.page || getEndpoint?.args?.per_page);
const hasSchema = Boolean(getEndpoint?.schema || routeDefinition?.schema);
// The generic shape heuristic (schema or pagination or 3+ path segments) exists to
// filter out config/dashboard noise when nothing else vouches for a route. A profile
// explicitly declaring a request override already is that vouching — same principle as
// profile-declared routes outranking the classifier's shape rules.
if (!requestOverride && !hasSchema && !supportsPagination && segments.length < 3) {
continue;
}
// Derive the file name from the full path after the namespace so distinct
// routes that share a last segment (e.g. /wp/v2/categories vs.
// /wp/v2/block-patterns/categories) do not collide onto one file.
const pathSlug = slugify(segments.slice(2).join('-')) || slugify(entityName);
candidates.push({
entityName,
namespace,
routePath,
endpoints,
getEndpoint,
routeDefinition,
supportsPagination,
requestOverride,
fileName: `${slugify(namespace)}--${pathSlug}.md`,
});
}
const unique = new Map();
for (const candidate of candidates) {
const key = `${candidate.namespace}:${candidate.routePath}`;
if (!unique.has(key)) {
unique.set(key, candidate);
}
}
return [...unique.values()].sort((a, b) => a.routePath.localeCompare(b.routePath));
}
// Finds every route named by a "$SAMPLED_IDS:<route>" placeholder anywhere
// inside a requestOverride body, however deeply nested. A body may reference more than one
// route (e.g. two independent id lists); collecting all of them, not just the first match, is
// what lets the pagination+batch mechanism below (lib/sampled-ids-batch.js) discover every
// route it must paginate to exhaustion rather than resolving one placeholder to []. Generic
// body-walk, no field names baked in.
function findSampledIdsDependencies(value, found = new Set()) {
if (Array.isArray(value)) {
for (const item of value) {
findSampledIdsDependencies(item, found);
}
} else if (value && typeof value === 'object') {
for (const nested of Object.values(value)) {
findSampledIdsDependencies(nested, found);
}
} else if (typeof value === 'string') {
const match = value.match(/^\$SAMPLED_IDS:(.+)$/);
if (match) found.add(match[1]);
}
return found;
}
// Resolves a dot-path ("data.items", "data.meta.count") against a response body for a
// responseEnvelope-declaring entity. Returns undefined on any missing/non-object segment
// rather than throwing, so an envelope path that stops matching (a plugin update, a stale
// profile) degrades to the safe fallback in inspectEntity instead of crashing the run.
function getAtPath(value, dotPath) {
return String(dotPath).split('.').reduce(
(acc, key) => (acc && typeof acc === 'object' ? acc[key] : undefined),
value,
);
}
// Deep-resolves a profile-declared requestBody template against a batch's ids. `idsByRoute` is
// a plain `{ route: string[] }` map — for the $SAMPLED_IDS mechanism this is
// always the CURRENT BATCH's ids for the route being paginated, resolved fresh per batch, never
// a fixed full list baked into one oversized request. Generic across any entity/route pair —
// the placeholder names the OTHER route's ids it wants, nothing plugin-specific lives here.
function resolveRequestBody(template, idsByRoute) {
if (Array.isArray(template)) {
return template.map((value) => resolveRequestBody(value, idsByRoute));
}
if (template && typeof template === 'object') {
const resolved = {};
for (const [key, value] of Object.entries(template)) {
resolved[key] = resolveRequestBody(value, idsByRoute);
}
return resolved;
}
if (typeof template === 'string') {
const match = template.match(/^\$SAMPLED_IDS:(.+)$/);
if (match) {
return (idsByRoute && idsByRoute[match[1]]) || [];
}
}
return template;
}
// Envelope resolution + fragment-group reassembly, shared by the single-fetch path below and
// by every batch of the paginate+batch path (lib/sampled-ids-batch.js) — one profile's response
// shape must normalize the same way regardless of which path fetched it. Pushes discovery
// notes only when `notes` is provided (batched callers pass it for the first batch only, since
// the shape characteristic belongs to the endpoint, not to any one batch). Returns `{ ok,
// records }`: `ok: false` means the payload did not resolve to an array after envelope
// resolution (when declared) and fragment reassembly (when declared) — a genuine shape
// mismatch, not "zero records" — and callers on the batched path must treat that as a failure
// to defer on, never silently as an empty batch (an enveloped response whose itemsPath
// mismatches would otherwise look like an authoritative, exact zero).
function normalizeResponseRecords(payload, { envelope, fragmentGroupSize, notes } = {}) {
let effectivePayload = payload;
if (envelope) {
const items = getAtPath(payload, envelope.itemsPath);
if (Array.isArray(items)) {
effectivePayload = items;
} else if (notes) {
notes.push(`responseEnvelope.itemsPath="${envelope.itemsPath}" did not resolve to an array on this response; falling back to the raw payload shape. The profile may be stale or the plugin version differs.`);
}
}
if (fragmentGroupSize && Array.isArray(effectivePayload)) {
const completeGroups = Math.floor(effectivePayload.length / fragmentGroupSize);
const reassembled = [];
for (let i = 0; i < completeGroups; i += 1) {
reassembled.push(Object.assign({}, ...effectivePayload.slice(i * fragmentGroupSize, (i + 1) * fragmentGroupSize)));
}
if (notes && effectivePayload.length % fragmentGroupSize !== 0) {
notes.push(`Response length ${effectivePayload.length} is not a multiple of the declared responseFragmentGroupSize=${fragmentGroupSize}; the trailing ${effectivePayload.length % fragmentGroupSize} fragment(s) were dropped rather than emitted as a broken record.`);
}
if (notes) {
notes.push(`Response records were flattened into groups of ${fragmentGroupSize} single-key fragments (per profile responseFragmentGroupSize) and reassembled into one object per record.`);
}
effectivePayload = reassembled;
}
const ok = Array.isArray(effectivePayload);
return { ok, records: ok ? effectivePayload : [] };
}
async function inspectEntity(baseUrl, headers, candidate, options) {
const details = {
entityName: candidate.entityName,
namespace: candidate.namespace,
routePath: candidate.routePath,
fileName: candidate.fileName,
classification: candidate.classification || null,
methods: [...new Set(candidate.endpoints.flatMap(endpointMethods))].sort(),
supportsPagination: candidate.supportsPagination,
discoveryNotes: [],
requestErrors: [],
collectionArgs: candidate.getEndpoint?.args || null,
schema: candidate.getEndpoint?.schema || candidate.routeDefinition?.schema || null,
optionsSchema: null,
sampleRecords: [],
sampleRecordCount: 0,
recordCount: null,
inUse: null,
relationships: [],
responseShape: 'unknown',
};
const optionsResponse = await fetchJson(baseUrl, candidate.routePath, {
headers,
method: 'OPTIONS',
timeoutMs: options.timeoutMs,
progress: options.progress,
progressContext: {
step: 'inspect-endpoint',
entity: candidate.routePath,
},
});
if (optionsResponse.ok && optionsResponse.json) {
const optionEndpoints = Array.isArray(optionsResponse.json?.endpoints) ? optionsResponse.json.endpoints : [];
const getEndpoint = optionEndpoints.find((endpoint) => endpointMethods(endpoint).includes('GET'));
if (getEndpoint?.args) {
details.collectionArgs = getEndpoint.args;
}
if (optionsResponse.json?.schema) {
details.optionsSchema = optionsResponse.json.schema;
details.schema = optionsResponse.json.schema;
} else if (getEndpoint?.schema) {
details.optionsSchema = getEndpoint.schema;
details.schema = getEndpoint.schema;
}
} else if (optionsResponse.status !== 404 && optionsResponse.status !== 405) {
details.requestErrors.push({
request: 'OPTIONS',
routePath: candidate.routePath,
status: optionsResponse.status,
statusText: optionsResponse.statusText,
url: optionsResponse.url,
});
}
// A profile may declare that this entity's real read path is a non-GET request with a
// JSON body — generic across any plugin/entity, not special-cased here.
const requestOverride = options.requestOverride || null;
const dependencyRoutes = requestOverride ? [...findSampledIdsDependencies(requestOverride.body)] : [];
if (requestOverride && dependencyRoutes.length > 0) {
// The $SAMPLED_IDS mechanism always means "paginate the dependency route to exhaustion,
// then batch-query this route" — the dependency's record count is unknown, so
// there is no bounded "small sample" variant that is safe to assume complete. This is the
// ENTIRE meaning of a $SAMPLED_IDS placeholder now, in both discovery and any generated
// reader (see rp-import-codegen's sourceMeta contract).
return inspectDependentEntity(baseUrl, headers, candidate, options, details, requestOverride, dependencyRoutes);
}
let sampleResponse;
if (requestOverride) {
// A fixed-body override with no $SAMPLED_IDS placeholder — single request, unbounded by
// definition since nothing here scales with another route's record count.
const resolvedBody = resolveRequestBody(requestOverride.body, {});
details.discoveryNotes.push(
`Sampled via profile-declared ${requestOverride.method} request with a JSON body, not a plain GET collection.`,
);
sampleResponse = await fetchJson(baseUrl, candidate.routePath, {
// `headers` is a real Headers instance (wp-http.js buildHeaders) — spreading it
// would silently drop every entry including Authorization, since Headers is not a
// plain object. Clone it properly instead.
headers: (() => {
const withBody = new Headers(headers);
withBody.set('content-type', 'application/json');
return withBody;
})(),
method: requestOverride.method,
body: JSON.stringify(resolvedBody),
timeoutMs: options.timeoutMs,
progress: options.progress,
progressContext: {
step: 'inspect-endpoint',
entity: candidate.routePath,
},
});
} else {
// Per-route default query (see ROUTE_DEFAULT_QUERY_RULES): some collection routes apply
// a default filter when the caller sends none, so sampling with `per_page` alone reads a
// subset and the plan under-counts. Paging is layered on top; a route with no rule is
// unchanged.
const defaultQuery = options.defaultQuery || {};
const query = {
...defaultQuery,
...(candidate.supportsPagination ? { per_page: options.sampleLimit } : {}),
};
if (Object.keys(defaultQuery).length > 0) {
const pairs = Object.entries(defaultQuery).map(([key, value]) => `${key}=${value}`).join('&');
const reason = options.defaultQueryReason ? ` — ${options.defaultQueryReason}` : '';
details.discoveryNotes.push(`Sampled with route default query ${pairs} so the full collection is counted${reason}. Generated readers must send the same parameters.`);
}
sampleResponse = await fetchJson(baseUrl, candidate.routePath, {
headers,
method: 'GET',
query,
timeoutMs: options.timeoutMs,
progress: options.progress,
progressContext: {
step: 'inspect-endpoint',
entity: candidate.routePath,
},
});
}
if (sampleResponse.ok) {
const payload = sampleResponse.json;
const totalFromHeader = parseTotalHeader(sampleResponse.headers);
// responseEnvelope support: some plugin REST APIs (MailPoet's
// /mailpoet/v1/* namespace, verified live 2026-08-11) wrap their records in a body path
// instead of returning a flat array, and carry no X-WP-Total/X-WP-TotalPages headers —
// the total lives inside the body too. Unwrap to the declared path and otherwise treat it
// exactly like a flat array; a path that no longer resolves (stale profile, plugin
// version drift) falls back to the raw payload rather than failing the run.
const envelope = options.responseEnvelope || null;
let effectivePayload = payload;
let envelopeCount = null;
if (envelope) {
const items = getAtPath(payload, envelope.itemsPath);
if (Array.isArray(items)) {
effectivePayload = items;
envelopeCount = envelope.countPath ? getAtPath(payload, envelope.countPath) : null;
} else {
details.discoveryNotes.push(`responseEnvelope.itemsPath="${envelope.itemsPath}" did not resolve to an array on this response; falling back to the raw payload shape. The profile may be stale or the plugin version differs.`);
}
}
// responseFragmentGroupSize support: some plugin REST APIs (Back In Stock Notifier's
// list_subscriber, verified live 2026-08-19) emit each logical record as N separate
// single-key array entries in sequence instead of one merged object. Reassemble every N
// entries into one record via Object.assign before anything downstream counts or samples
// — a reader built from a stale sample would otherwise see 4x the real record count and a
// schema missing whichever key happened to be sampled out of order. A trailing partial
// group (malformed response, plugin bug) is dropped and noted rather than emitted broken.
const fragmentGroupSize = options.responseFragmentGroupSize || null;
if (fragmentGroupSize && Array.isArray(effectivePayload)) {
effectivePayload = normalizeResponseRecords(effectivePayload, { fragmentGroupSize, notes: details.discoveryNotes }).records;
}
if (Array.isArray(effectivePayload)) {
details.responseShape = envelope && effectivePayload !== payload ? 'enveloped-array' : 'array';
details.sampleRecords = effectivePayload.slice(0, options.sampleLimit);
details.sampleRecordCount = effectivePayload.length;
const hasEnvelopeCount = typeof envelopeCount === 'number';
details.recordCount = hasEnvelopeCount ? envelopeCount : (totalFromHeader !== null ? totalFromHeader : effectivePayload.length);
details.inUse = details.recordCount > 0;
if (details.responseShape === 'enveloped-array' && !hasEnvelopeCount) {
details.discoveryNotes.push(`responseEnvelope has no working countPath (itemsPath="${envelope.itemsPath}"); recordCount reflects only the sampled page and may undercount the true total.`);
} else if (details.responseShape === 'array' && totalFromHeader === null) {
details.discoveryNotes.push('No X-WP-Total header returned; recordCount reflects only the sampled page and may undercount the true total.');
}
if (candidate.routePath.startsWith('/wc/store/v1/') && !Object.keys(sampleResponse.headers || {}).some((key) => key.toLowerCase() === 'x-wp-totalpages')) {
details.discoveryNotes.push('WooCommerce Store API route does not advertise X-WP-TotalPages; generated readers must stop on a short page when bulk-extracting this entity.');
}
if (effectivePayload.length === 0) {
details.discoveryNotes.push('Endpoint returned an empty array. The entity is advertised but appears unused (no records).');
}
} else if (effectivePayload && typeof effectivePayload === 'object') {
details.responseShape = 'object';
details.sampleRecords = [effectivePayload];
details.sampleRecordCount = 1;
details.recordCount = totalFromHeader !== null ? totalFromHeader : 1;
details.inUse = details.recordCount > 0;
} else {
details.responseShape = typeof effectivePayload;
details.discoveryNotes.push(`Endpoint returned a non-object payload of type ${typeof effectivePayload}.`);
}
const firstRecord = details.sampleRecords[0];
if (firstRecord && typeof firstRecord === 'object') {
details.relationships = summarizeRelationships(firstRecord);
}
} else {
details.requestErrors.push({
request: requestOverride ? requestOverride.method : 'GET',
routePath: candidate.routePath,
status: sampleResponse.status,
statusText: sampleResponse.statusText,
url: sampleResponse.url,
body: sampleResponse.text ? sampleResponse.text.slice(0, 1000) : '',
});
}
return details;
}
// Paginates every $SAMPLED_IDS dependency route to exhaustion, then batch-queries `candidate`'s
// route — split out of inspectEntity because it is a fundamentally different shape
// (two routes, many requests, an explicit fail/defer path) from a single-fetch inspection.
// Assumes a single batching axis: when a body references more than one dependency route, only
// the first drives batching (noted below) — no known profile needs two independent id lists
// batched together, and this stays honest about that boundary rather than guessing a policy.
async function inspectDependentEntity(baseUrl, headers, candidate, options, details, requestOverride, dependencyRoutes) {
const batchRoute = dependencyRoutes[0];
if (dependencyRoutes.length > 1) {
details.discoveryNotes.push(
`requestBody references multiple $SAMPLED_IDS routes (${dependencyRoutes.join(', ')}); only the first, ${batchRoute}, drives pagination/batching — a profile needing more than one independent id list is not yet supported generically.`,
);
}
const paged = await collectAllIds({
baseUrl,
headers,
route: batchRoute,
timeoutMs: options.timeoutMs,
progress: options.progress,
});
if (!paged.ok) {
// Fail/defer explicitly: recordCount/inUse stay at their initial `null`, which
// is this codebase's existing "unknown, not zero" signal, backed by a requestErrors entry
// explaining exactly which page of which route failed — never a false empty or a silent
// undercount from whatever ids were collected before the failure.
details.requestErrors.push({
request: 'GET',
routePath: paged.failure.route,
status: paged.failure.status,
statusText: paged.failure.statusText,
url: null,
body: `Failed while paginating the $SAMPLED_IDS dependency route ${paged.failure.route} at page ${paged.failure.page}. ${candidate.routePath}'s record count and schema are unknown and must be treated as deferred, not reported as empty.`,
});
return details;
}
details.discoveryNotes.push(
`Sampled via profile-declared ${requestOverride.method} request with a JSON body, against the FULL paginated id list of ${batchRoute} (${paged.ids.length} ids across ${Math.ceil(paged.ids.length / DEFAULT_BATCH_SIZE)} batches of up to ${DEFAULT_BATCH_SIZE}) rather than a fixed small sample.`,
);
let shapeNotesEmitted = false;
const batched = await queryInBatches({
baseUrl,
headers,
route: candidate.routePath,
method: requestOverride.method,
ids: paged.ids,
recordKeyField: options.recordKeyField || 'id',
buildBody: (batchIds) => resolveRequestBody(requestOverride.body, { [batchRoute]: batchIds.map(String) }),
// Pass the RAW batch JSON through — response.json may be an enveloped object, not an
// array, and normalizeResponseRecords (not this callback) is what unwraps it. Returning
// its {ok, records} result unchanged is what lets queryInBatches distinguish "this batch's
// response didn't match the declared shape" from "this batch legitimately matched zero
// subscribers" and defer on the former instead of counting it as an exact zero.
normalizeBatch: (rawJson) => {
const normalized = normalizeResponseRecords(rawJson, {
envelope: options.responseEnvelope,
fragmentGroupSize: options.responseFragmentGroupSize,
notes: shapeNotesEmitted ? null : details.discoveryNotes,
});
shapeNotesEmitted = true;
return normalized;
},
timeoutMs: options.timeoutMs,
progress: options.progress,
});
if (!batched.ok) {
const shapeFailure = batched.failure.reason === 'invalid-shape';
details.requestErrors.push({
request: requestOverride.method,
routePath: batched.failure.route,
status: batched.failure.status,
statusText: batched.failure.statusText,
url: null,
body: shapeFailure
? `Batch ${batched.failure.batchIndex + 1} (${batched.failure.batchSize} ids) returned a ${batched.failure.status} response that did not match the declared response shape (responseEnvelope/responseFragmentGroupSize). Batches already merged before this failure are discarded — ${candidate.routePath}'s record count and schema are unknown and must be treated as deferred, not reported as an exact zero.`
: `Failed on batch ${batched.failure.batchIndex + 1} (${batched.failure.batchSize} ids). Batches already merged before this failure are discarded — ${candidate.routePath}'s record count and schema are unknown and must be treated as deferred, not reported as a partial undercount.`,
});
return details;
}
details.responseShape = 'array';
details.sampleRecords = batched.records.slice(0, options.sampleLimit);
details.sampleRecordCount = batched.records.length;
// Exact, not an estimate: every dependency id was queried and every batch's records were
// deduplicated, unlike the sampled-page count elsewhere in this function.
details.recordCount = batched.records.length;
details.inUse = details.recordCount > 0;
details.discoveryNotes.push('recordCount reflects the full deduplicated merge across every batch of the complete dependency id list, not a sampled page — this total is exact.');
if (batched.records.length === 0) {
details.discoveryNotes.push('No records matched any batch across the full paginated dependency id list. The entity is advertised but appears unused (no records).');
}
const firstRecord = details.sampleRecords[0];
if (firstRecord && typeof firstRecord === 'object') {
details.relationships = summarizeRelationships(firstRecord);
}
return details;
}
function markdownJsonBlock(value) {
if (value === null || value === undefined) {
return '\n\n`Unavailable`';
}
return `\n\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
}
function renderEntityFile(details) {
const errorLines = details.requestErrors.length > 0
? details.requestErrors.map((error) => `- ${error.request} ${error.routePath}: ${error.status} ${error.statusText}`).join('\n')
: '- None';
const notes = details.discoveryNotes.length > 0
? details.discoveryNotes.map((note) => `- ${note}`).join('\n')
: '- None';
const relationshipLines = details.relationships.length > 0
? details.relationships
.map((relationship) => `- \`${relationship.rel}\`${relationship.embeddable ? ' (embeddable)' : ''} → ${relationship.hrefs.join(', ')}`)
.join('\n')
: '- None detected (no `_links` in sample record)';
const recordCountLabel = details.recordCount === null ? 'unknown' : String(details.recordCount);
const inUseLabel = details.inUse === null ? 'unknown' : details.inUse ? 'yes' : 'no (advertised but empty)';
const classificationLines = details.classification
? `- Discovery category: \`${details.classification.category}\`\n` +
`- Discovery rule: \`${details.classification.ruleId}\`\n` +
`- Discovery reason: ${details.classification.reason}\n` +
`- Included by override: \`${details.classification.includedByOverride ? 'yes' : 'no'}\`\n` +
`- Excluded by override: \`${details.classification.excludedByOverride ? 'yes' : 'no'}\`\n`
: '';
return `# ${details.entityName}\n\n` +
`- Namespace: \`${details.namespace}\`\n` +
`- Route: \`${details.routePath}\`\n` +
classificationLines +
`- Methods: ${details.methods.map((method) => `\`${method}\``).join(', ') || '`unknown`'}\n` +
`- Response shape: \`${details.responseShape}\`\n` +
`- Record count: \`${recordCountLabel}\`\n` +
`- In use: \`${inUseLabel}\`\n` +
`- Sample records captured: ${details.sampleRecords.length}\n\n` +
`## Notes\n${notes}\n\n` +
`## Relationships\n${relationshipLines}\n\n` +
`## Request Errors\n${errorLines}\n\n` +
`## Schema${markdownJsonBlock(details.schema)}\n\n` +
`## Collection Args${markdownJsonBlock(details.collectionArgs)}\n\n` +
`## Sample Records${markdownJsonBlock(details.sampleRecords)}\n`;
}
function renderPluginSection(context) {
if (!context.plugins) {
return `## Plugin Coverage\n\nPlugin inventory was not run for this capture.\n\n`;
}
const { detection, coverage, summary, unprofiled } = context.plugins;
const rows = coverage
.map((row) => {
const via = row.status === 'migration-planned' ? `${row.via} · ${row.confidence}` : '-';
const blocked = (row.blocked || []).length > 0
? row.blocked.map((blocker) => `${blocker.kind}${blocker.declined ? ' (declined)' : ''}`).join(', ')
: '-';
return `| ${row.capability} | \`${row.status}\` | ${via} | ${row.recognized ? 'yes' : 'no'} | ${row.plugins.join(', ') || '-'} | \`${row.channel || 'none'}\` | ${blocked} | ${row.action ? row.action : '-'} |`;
})
.join('\n');
const authNote = detection.pluginListAvailable
? ''
: `**\`GET /wp/v2/plugins\` was unavailable**, so installed-but-unprofiled plugins could not be enumerated. ` +
`Detection used REST namespaces, declared routes, registered types/taxonomies, and public asset paths only. ` +
`Re-run with an administrator credential for a complete plugin list.\n\n`;
const installedRows = detection.installedButUnprofiled
.map((entry) => `- \`${entry.plugin}\`${entry.name ? ` (${entry.name})` : ''}${entry.active ? '' : ' — inactive'}`)
.join('\n') || '- None';
const unprofiledRows = unprofiled
.map((entry) => `- \`${entry.namespace}\`: ${entry.routes.length} route(s) accepted by shape`)
.join('\n') || '- None';
return `## Plugin Coverage\n\n` +
authNote +
`- Recognized plugins detected: ${detection.detected.length}\n` +
`- Derived entities (no profile): ${context.plugins.genericEntities.length}\n` +
`- Unprofiled namespaces: ${unprofiled.length}\n` +
`- Installed but unrecognized: ${detection.installedButUnprofiled.length}\n` +
`- Publicly fingerprinted (named, not enumerated): ${(detection.fingerprinted || []).length}\n` +
`- Capabilities by status: ${Object.entries(summary.byStatus).map(([status, count]) => `\`${status}\`: ${count}`).join(', ') || 'none'}\n\n` +
`| Capability | Status | Via | Recognized | Plugins | Channel | Blocked | Action needed |\n` +
`| --- | --- | --- | --- | --- | --- | --- | --- |\n` +
`${rows || '| None | - | - | - | - | - | - | - |'}\n\n` +
`### Installed but unprofiled\n\n${installedRows}\n\n` +
`### Unprofiled namespaces accepted by shape\n\n${unprofiledRows}\n\n` +
`Full coverage evidence: [plugin-coverage.json](./plugin-coverage.json) · ` +
`detection evidence: [plugin-inventory.json](./plugin-inventory.json)\n\n`;
}
function renderIndexFile(context) {
const entityRows = context.entities.map((entity) => {
const status = entity.requestErrors.length > 0 ? 'partial' : 'ok';
const recordCountLabel = entity.recordCount === null ? '?' : String(entity.recordCount);
const inUseLabel = entity.inUse === null ? '?' : entity.inUse ? 'yes' : 'no';
return `| ${entity.entityName} | \`${entity.namespace}\` | \`${entity.routePath}\` | ${recordCountLabel} | ${inUseLabel} | ${entity.sampleRecords.length} | ${status} | [${entity.fileName}](./${entity.fileName}) |`;
}).join('\n');
const errorLines = context.entities
.flatMap((entity) => entity.requestErrors.map((error) => `- ${entity.entityName}: ${error.request} ${error.routePath} -> ${error.status} ${error.statusText}`));
const skippedByCategoryLines = Object.entries(context.skippedByCategory || {})
.map(([category, count]) => `- \`${category}\`: ${count}`)
.join('\n') || '- None';
const overrideLines = [
`- Include routes: ${context.overrides.includeRoutes.map((route) => `\`${route}\``).join(', ') || '`none`'}`,
`- Include namespaces: ${context.overrides.includeNamespaces.map((namespace) => `\`${namespace}\``).join(', ') || '`none`'}`,
`- Include excluded categories: ${context.overrides.includeExcludedCategories.map((category) => `\`${category}\``).join(', ') || '`none`'}`,
`- Exclude routes: ${context.overrides.excludeRoutes.map((route) => `\`${route}\``).join(', ') || '`none`'}`,
`- Override reason: ${context.overrides.overrideReason ? context.overrides.overrideReason : '`none`'}`,
].join('\n');
const authGatedEntities = context.entities.filter((entity) =>
entity.requestErrors.some((error) => error.status === 401 || error.status === 403));
const authWarning = authGatedEntities.length > 0
? `## ⚠️ Incomplete Capture (Authentication)\n\n` +
`${authGatedEntities.length} entit${authGatedEntities.length === 1 ? 'y' : 'ies'} returned 401/403 and ` +
`could not be captured` +
`${context.authMode === 'none' ? ' — this run used **no credentials**' : ` with auth mode \`${context.authMode}\` (insufficient scope)`}.\n` +
`Their \`recordCount\`/\`inUse\` are unreliable: an auth-gated entity can look empty or errored even when the site uses it heavily (e.g. WooCommerce orders/customers, drafts, private fields).\n` +
`Re-run with credentials for a complete and trustworthy capture.\n\n` +
`Auth-gated entities: ${authGatedEntities.map((entity) => `\`${entity.entityName}\``).join(', ')}\n\n`
: '';
const pluginSection = renderPluginSection(context);
return `# WordPress Discovery\n\n` +
`- Generated at: \`${context.generatedAt}\`\n` +
`- Base URL: \`${context.baseUrl}\`\n` +
`- REST root: \`${context.restRoot}\`\n` +
`- Auth mode: \`${context.authMode}\`\n` +
`- Advertised auth providers: ${context.authProviders.map((provider) => `\`${provider}\``).join(', ') || '`none`'}\n` +
`- Namespaces advertised: ${context.namespaces.map((namespace) => `\`${namespace}\``).join(', ') || '`none`'}\n` +
`- Advertised routes: ${context.totalAdvertisedRoutes}\n` +
`- Candidate routes after generic filtering: ${context.totalCandidateRoutes}\n` +
`- Sampled backend data/metadata routes: ${context.sampledRoutes}\n` +
`- Skipped routes: ${context.skippedRoutes}\n` +
`- Entities documented: ${context.entities.length}\n\n` +
authWarning +
`## Route Scope\n\n` +
`### Skipped Routes by Category\n\n${skippedByCategoryLines}\n\n` +
`### Overrides\n\n${overrideLines}\n\n` +
`Skipped route evidence: [skipped-routes.json](./skipped-routes.json)\n\n` +
pluginSection +
`## Discovery Summary\n\n` +
`| Entity | Namespace | Route | Records | In use | Samples | Status | File |\n` +
`| --- | --- | --- | ---: | --- | ---: | --- | --- |\n` +
`${entityRows || '| None | - | - | - | - | 0 | - | - |'}\n\n` +
`## Route Index Sample${markdownJsonBlock(context.routeIndexSample)}\n\n` +
`## Errors\n${errorLines.length > 0 ? errorLines.join('\n') : '- None'}\n`;
}
function skippedRoutesPayload(context) {
return {
generatedAt: context.generatedAt,
totalAdvertisedRoutes: context.totalAdvertisedRoutes,
totalCandidateRoutes: context.totalCandidateRoutes,
sampledRoutes: context.sampledRoutes,
skippedRoutes: context.skippedRoutes,
overrides: context.overrides,
routes: context.classifications
.filter((classification) => classification.effectiveAction === 'skip')
.map((classification) => ({
routePath: classification.routePath,
namespace: classification.namespace,
category: classification.category,
reason: classification.reason,
ruleId: classification.ruleId,
sampleByDefault: classification.sampleByDefault,
canIncludeByOverride: classification.canIncludeByOverride,
includedByOverride: classification.includedByOverride,
excludedByOverride: classification.excludedByOverride,
effectiveAction: classification.effectiveAction,
duplicateOf: classification.duplicateOf,
overrideReason: classification.overrideReason,
})),
};
}
// orchestration/decisions.json sits two levels above the discovery out-dir in the standard
// layout (migrations/<project>/data/wp-discovery); --decisions overrides. Missing or
// unparseable files mean "no answers yet", never an error — the ask may not have run.
function loadDecisions(args) {
const filePath = args.decisions
|| (args.outDir ? path.resolve(args.outDir, '..', '..', 'orchestration', 'decisions.json') : null);
if (!filePath) return {};
try {
return JSON.parse(require('node:fs').readFileSync(filePath, 'utf8'));
} catch {
return {};
}
}
// The batched ask (J1 step 9) records one decision per blocker under the key
// `pluginBlocker:<capability>:<kind>`; a value of `declined` (or `skipped`) marks it declined.
function applyBlockerDecisions(rows, decisions) {
for (const row of rows) {
for (const blocker of row.blocked || []) {
const entry = decisions[`pluginBlocker:${row.capability}:${blocker.kind}`];
if (entry && ['declined', 'skipped'].includes(entry.value)) blocker.declined = true;
}
}
}
function loadTargetKnowledge(domainsDir = null) {
try {
const {
knowledgeRoot,
knowledgeSummary,
} = require('../../rp-target-wix/lib/domain-knowledge.js');
return knowledgeSummary(domainsDir || knowledgeRoot(path.resolve(__dirname, '..', '..', 'rp-target-wix')));
} catch (error) {
// A partial install must not break discovery; coverage then reports CMS/native-gap
// conservatively instead of resolving target refs.
return { knownRefs: new Set(), capabilityRefs: new Map(), verificationByRef: new Map(), loadError: error.message };
}
}
// The record-count note a route's sample left (e.g. no X-WP-Total header), if any.
function countNoteOf(sampled) {
return (sampled.discoveryNotes || []).find((note) => /recordCount|undercount|record count/i.test(note)) || null;
}
// Durable record counts and sample evidence, one key per route of every detected plugin's
// profile entities (null when the route was not sampled). This is what lets coverage be
// reclassified later without a source fetch and without silently dropping counts.
function buildEntityStats(detection, sampledByRoute) {
const stats = {};
for (const plugin of detection?.detected || []) {
for (const entity of plugin.entities || []) {
if (!entity.route) continue;
const sampled = sampledByRoute.get(entity.route);
stats[entity.route] = sampled ? {
recordCount: sampled.recordCount ?? null,
inUse: sampled.inUse ?? null,
sampleRecordCount: sampled.sampleRecordCount ?? (sampled.sampleRecords || []).length,
countNote: countNoteOf(sampled),
} : null;
}
}
return Object.fromEntries(Object.entries(stats).sort(([a], [b]) => a.localeCompare(b)));
}
function entityStatsMap(entityStats) {
return new Map(Object.entries(entityStats || {}).filter(([, value]) => value && typeof value === 'object'));
}
// Malformed `pluginCmsFallback:*` keys with no row to carry them (capability not detected, or
// not eligible): listed once at the top level so the mapping review can show them.
function cmsFallbackDecisionIssues(rows, decisions) {
const carried = new Set(rows.filter((row) => row.recognized && row.cmsFallback).map((row) => row.capability));
const issues = [];
for (const key of cmsFallbackDecisionKeys(decisions)) {
const shape = cmsFallbackDecisionShape(key, decisions[key]);
if (shape.ok || carried.has(cmsFallbackCapabilityOfKey(key))) continue;
issues.push({ key, problem: shape.problem });
}
return issues;
}
function cmsFallbackDigestFor({ inventory, profiles, targetKnowledge, knowledgeDir, hints, decisions }) {
return cmsFallbackInputsDigest(cmsFallbackResolutionInputs({
detectedPlugins: detectedPluginsOf(inventory),
profiles,
targetKnowledge,
registers: {
cmsFallbackEligible: loadCmsFallbackEligible(knowledgeDir).capabilities || [],
requiresDevelopment: loadRequiresDevelopment(knowledgeDir).capabilities || [],
noMigrationNeeded: hints,
},
decisions,
}));
}
// The project root a raw discovery directory belongs to (`<project>/data/wp-discovery`), or null.
function projectDirOfOutDir(outDir) {
if (!outDir) return null;
const resolved = path.resolve(outDir);
return path.basename(resolved) === 'wp-discovery' && path.basename(path.dirname(resolved)) === 'data'
? path.resolve(resolved, '../..') : null;
}
// Tier C input: the project's canonical source-schema.json entities, where project-local bridge
// read plans (PLUGIN-READ-PLANS.md) record an unprofiled plugin's own tables. Missing or
// unreadable means none; this never reads the source site.
function readProjectSourceEntities(projectDir) {
if (!projectDir) return [];
try {
const schema = JSON.parse(require('node:fs').readFileSync(path.join(projectDir, 'source-schema.json'), 'utf8'));
return schema && schema.entities ? schema.entities : [];
} catch {
return [];
}
}
// Plugin detection, Tier-B derivation, and coverage classification, run after sampling so
// record payloads are available for core-embedded plugins that add no REST route.
// Routes this run really read: a sample came back (a known shape or a record count) and no
// read request failed. An inspected route that answered 401/403/500 is not read, so it never
// marks a coreCovered plugin (WooCommerce) as covered. OPTIONS failures do not count: the
// schema probe is optional and the read itself may still succeed.
function readRoutePaths(entities) {
return (entities || []).filter((entity) => {
if (!entity) return false;
const readFailed = (entity.requestErrors || []).some((error) => error && error.request !== 'OPTIONS');
const sampled = (entity.responseShape !== undefined && entity.responseShape !== 'unknown')
|| (entity.recordCount !== undefined && entity.recordCount !== null);
return sampled && !readFailed;
}).map((entity) => entity.routePath || entity.route).filter(Boolean);
}
function buildPluginCoverage({ args, inventory, classifications, entities, allCandidates = [], dataPresenceObservations = [] }) {
const knowledgeDir = args.pluginsRoot ? path.resolve(args.pluginsRoot) : pluginsRoot(path.resolve(__dirname, '..'));
const profiles = loadProfiles(knowledgeDir);
const sampledRecordProperties = collectRecordProperties(entities);
const detection = detectPlugins({
profiles,
restIndex: inventory.restIndex,
pluginList: inventory.detection.pluginListAvailable ? inventory.pluginList : null,
types: inventory.types,
taxonomies: inventory.taxonomies,
htmlSources: inventory.htmlSources || [],
sampledRecordProperties,
fingerprintAliases: loadFingerprintAliases(knowledgeDir),
});
const sampledByRoute = new Map(entities.map((entity) => [entity.routePath, entity]));
const unprofiled = [
...collectUnprofiledRoutes({ classifications, detection }),
...collectCandidateNamespaces({ classifications, candidates: allCandidates, detection }),
];
const genericEntities = deriveGenericEntities({
types: inventory.types,
taxonomies: inventory.taxonomies,
classifications,
detection,
sampledByRoute,
});
const targetKnowledge = loadTargetKnowledge(args.targetKnowledgeRoot ? path.resolve(args.targetKnowledgeRoot) : null);
const hints = loadNoMigrationNeeded(knowledgeDir);
const cutoverTasks = loadCutoverTasks(knowledgeDir);
const decisions = loadDecisions(args);
const bridgeEntities = deriveBridgePlannedEntities({
sourceEntities: readProjectSourceEntities(projectDirOfOutDir(args.outDir)),
detection,
capabilityRefs: targetKnowledge.capabilityRefs,
});
const rows = classifyCoverage({
detection,
genericEntities,
bridgeEntities,
unprofiledRoutes: unprofiled,
targetKnowledge,
entityStatsByRoute: sampledByRoute,
// Only human-signed verdicts may produce a requires-development status.
requiresDevelopmentEntries: loadRequiresDevelopment(knowledgeDir).capabilities || [],
// Working notes for profiled capabilities we have not placed yet.
pendingNotes: loadPendingDecisions(knowledgeDir).capabilities || [],
// Nothing-to-move verdicts, both tiers: the slug list resolves unprofiled plugins into
// rows (basis: list), and the signed capabilities[] register resolves profiled
// capabilities a human decided need no migration (basis: decision).
noMigrationNeeded: hints,
// CMS fallback: the signed eligibility register plus this run's merchant answers
// (`pluginCmsFallback:<capability>`). Neither alone plans a CMS write.
cmsFallbackEntries: loadCmsFallbackEligible(knowledgeDir).capabilities || [],
cmsFallbackDecisions: decisions,
// No-data plugins that need a named cutover task, and the routes this run read
// (a coreCovered plugin such as WooCommerce is covered only when its namespace was read).
cutoverTasks,
readRoutes: readRoutePaths(entities),
dataPresence: presenceByPlugin({ profiles, detection, observations: dataPresenceObservations }),
});
// Read back the batched-ask answers so a declined blocker renders as declined, never as
// unanswered. A declined blocker stays on the row — skipping is an answer, not silence.
applyBlockerDecisions(rows, decisions);
// One row per installed plugin, for customer review and for debugging this run later.
const dispositionRows = buildDispositionRows({
detection,
coverage: rows,
profiles,
hints,
cutoverTasks,
});
return {
detection,
genericEntities,
bridgeEntities,
unprofiled,
sampledRecordProperties,
coverage: rows,
summary: coverageSummary(rows),
disposition: dispositionRows,
dispositionSummary: summarizeDispositions(dispositionRows),
toolkitExcluded: toolkitExcludedCount(detection, hints),
targetKnowledgeError: targetKnowledge.loadError || null,
entityStats: buildEntityStats(detection, sampledByRoute),
cmsFallbackDecisionIssues: cmsFallbackDecisionIssues(rows, decisions),
cmsFallbackDigest: cmsFallbackDigestFor({ inventory: detection, profiles, targetKnowledge, knowledgeDir, hints, decisions }),
profiles,
dataPresenceObservations,
};
}
// run the dataPresence checks of every detected profile that declares them. REST
// checks use the run's credentials; postmeta/posts checks need wix-wp-plugin-v2 and come back
// `unknown` without it (never "empty").
async function collectDataPresence({ args, headers, namespaces, profiles, detection }) {
const fetchRest = async (routePath, query) => fetchJson(args.baseUrl, routePath, {
headers, method: 'GET', query, timeoutMs: args.timeoutMs, progress,
progressContext: { step: 'plugin-data-presence', entity: routePath },
});
let bridgeQuery = null;
if (namespaces.includes('wix-wp-plugin/v2')) {
const bridge = createBridgeTransport({ baseUrl: args.baseUrl, headers, timeoutMs: args.timeoutMs, progress });
bridgeQuery = async (structureRequest, cursor, limit) => queryStructure({
httpClient: bridge.httpClient, siteBaseUrl: args.baseUrl, auth: bridge.auth, structureRequest, cursor, limit,
});
}
return collectPresenceObservations({ profiles, detection, fetchRest, bridgeQuery });
}
/**
* Rebuild plugin coverage with no source network calls, after a CMS-fallback answer or a change
* to what could resolve an in-scope capability. Inputs are durable artifacts only: the stored
* detection (plugin-inventory.json), the prior coverage's entityStats and review evidence (copied
* forward unchanged), and the CURRENT profiles, registers, target knowledge and decisions.
* Returns { outcome: 'needs-full-discovery', reason } instead of a payload whenever the stored
* evidence cannot carry every count; it never writes a row with counts silently dropped.
*/
function reclassifyPluginCoverage({ prior, inventory, decisions = {}, pluginsRoot: pluginsDir = null, targetKnowledgeRoot = null, sourceEntities = [], redirectCaptureCoverage = null, generatedAt = new Date().toISOString() }) {
if (!prior || !prior.entityStats || typeof prior.entityStats !== 'object' || Array.isArray(prior.entityStats)) {
return { outcome: 'needs-full-discovery', reason: 'prior plugin-coverage.json has no entityStats' };
}
if (!inventory || !Array.isArray(inventory.detected)) {
return { outcome: 'needs-full-discovery', reason: 'plugin-inventory.json is missing or has no detected[]' };
}
const knowledgeDir = pluginsDir || pluginsRoot(path.resolve(__dirname, '..'));
const profiles = loadProfiles(knowledgeDir);
const profileBySlug = new Map(profiles.map((profile) => [profile.plugin, profile]));
const targetKnowledge = loadTargetKnowledge(targetKnowledgeRoot);
const hints = loadNoMigrationNeeded(knowledgeDir);
const cutoverTasks = loadCutoverTasks(knowledgeDir);
const aliases = loadFingerprintAliases(knowledgeDir).aliases || {};
const cmsFallbackEntries = loadCmsFallbackEligible(knowledgeDir).capabilities || [];
const requiresDevelopmentEntries = loadRequiresDevelopment(knowledgeDir).capabilities || [];
const sampledRoutes = new Set(Object.keys(prior.entityStats).filter((route) => prior.entityStats[route]));
const detected = inventory.detected.map((stored) => {
const profile = profileBySlug.get(stored.plugin);
// A detected plugin whose profile left the repo keeps its capabilities but declares no
// entities, so nothing can resolve for it and no CMS plan survives.
if (!profile) return { ...stored, entities: [] };
return {
...stored,
displayName: profile.displayName || stored.displayName,
capabilities: [...(profile.capabilities || [])],
profileVersion: profile.profileVersion || stored.profileVersion,
// The current profile decides where the data lives (a stored run may predate the field).
dataLocation: profile.dataLocation || null,
entities: (profile.entities || []).map((entity) => {
const described = describeProfiledEntity(entity, {
routes: sampledRoutes,
rawRoutes: {},
properties: new Set(),
apiBelowMinVersion: stored.apiBelowMinVersion === true,
});
const previous = (stored.entities || []).find((candidate) => candidate.entity === entity.entity
&& candidate.channel === entity.channel && (candidate.route || null) === (entity.route || null));
return previous ? { ...described, channelStatus: previous.channelStatus } : described;
}),
};
});
const inputs = cmsFallbackResolutionInputs({
detectedPlugins: detectedPluginsOf(inventory),
profiles,
targetKnowledge,
registers: { cmsFallbackEligible: cmsFallbackEntries, requiresDevelopment: requiresDevelopmentEntries, noMigrationNeeded: hints },
decisions,
});
for (const capability of Object.keys(inputs.capabilities)) {
for (const plugin of detected.filter((candidate) => (candidate.capabilities || []).includes(capability))) {
for (const entity of plugin.entities) {
if (entity.route && !Object.prototype.hasOwnProperty.call(prior.entityStats, entity.route)) {
return { outcome: 'needs-full-discovery', reason: `route ${entity.route} of ${plugin.plugin} (${capability}) has no stored entityStats` };
}
}
}
}
const detection = {
pluginListAvailable: inventory.pluginListAvailable === true,
detected,
installedButUnprofiled: inventory.installedButUnprofiled || [],
// Re-resolved through the CURRENT alias map, so an alias added after discovery
// (ctxfeed -> CTX Feed) folds a stored fingerprint into its installed plugin.
fingerprinted: (inventory.fingerprinted || []).map((print) => refreshFingerprint(print, aliases)),
};
// Tier C is re-derived from the CURRENT source schema: a project-local read plan written after
// discovery is exactly the change this rebuild exists to pick up.
const bridgeEntities = deriveBridgePlannedEntities({ sourceEntities, detection, capabilityRefs: targetKnowledge.capabilityRefs });
const rows = classifyCoverage({
detection,
genericEntities: prior.genericEntities || [],
bridgeEntities,
unprofiledRoutes: prior.unprofiledRoutes || [],
targetKnowledge,
entityStatsByRoute: entityStatsMap(prior.entityStats),
requiresDevelopmentEntries,
pendingNotes: loadPendingDecisions(knowledgeDir).capabilities || [],
noMigrationNeeded: hints,
cmsFallbackEntries,
cmsFallbackDecisions: decisions,
cutoverTasks,
readRoutes: readRoutePaths(Array.isArray(sourceEntities) ? sourceEntities : Object.values(sourceEntities || {})),
// Stored observations only: a rebuild never re-reads the site.
dataPresence: presenceByPlugin({ profiles, detection, observations: prior.dataPresence || [] }),
});
applyBlockerDecisions(rows, decisions);
const annotated = redirectCaptureCoverage
? redirectSources.annotateRedirectCoverageRows(rows, redirectCaptureCoverage, { providers: redirectSources.providersFromProfiles(profiles) })
: rows;
rows.splice(0, rows.length, ...annotated);
const disposition = buildDispositionRows({ detection, coverage: rows, profiles, hints, cutoverTasks });
return {
outcome: 'reclassified',
payload: {
...prior,
generatedAt,
summary: coverageSummary(rows),
perPluginSummary: summarizeDispositions(disposition),
capabilities: rows,
perPlugin: disposition,
statusInvariant: { ...(prior.statusInvariant || {}), toolkitExcluded: toolkitExcludedCount(detection, hints) },
bridgeEntities,
cmsFallbackDecisionIssues: cmsFallbackDecisionIssues(rows, decisions),
inputs: { ...(prior.inputs || {}), cmsFallbackDigest: cmsFallbackInputsDigest(inputs), reclassifiedFrom: prior.generatedAt || null },
},
};
}
function refreshFingerprint(print, aliases) {
const alias = print && aliases[print.token];
if (!alias) return print;
return { ...print, displayName: alias.displayName, slug: alias.slug, aliasMatched: true };
}
function toolkitExcludedCount(detection, hints) {
const toolkit = new Set((hints?.toolkitPlugins || []).filter((entry) => entry && entry.decidedBy && entry.decidedOn).map((entry) => entry.slug));
return (detection?.installedButUnprofiled || []).filter((entry) => registerKeys(entry.plugin).some((key) => toolkit.has(key))).length;
}
async function runReclassifyCoverage(args) {
if (!args.outDir) throw new Error('--reclassify-coverage requires --out-dir (the raw discovery directory)');
const outDir = path.resolve(args.outDir);
const readOrNull = async (filePath) => {
try {
return JSON.parse(await fs.readFile(filePath, 'utf8'));
} catch {
return null;
}
};
const result = reclassifyPluginCoverage({
prior: await readOrNull(path.join(outDir, 'plugin-coverage.json')),
inventory: await readOrNull(path.join(outDir, 'plugin-inventory.json')),
decisions: loadDecisions({ ...args, outDir }),
pluginsRoot: args.pluginsRoot ? path.resolve(args.pluginsRoot) : null,
targetKnowledgeRoot: args.targetKnowledgeRoot ? path.resolve(args.targetKnowledgeRoot) : null,
sourceEntities: readProjectSourceEntities(projectDirOfOutDir(outDir)),
redirectCaptureCoverage: readRecordedRedirectCoverage(projectDirOfOutDir(outDir)),
});
if (result.outcome !== 'reclassified') return result;
const text = `${JSON.stringify(result.payload, null, 2)}\n`;
const targets = [path.join(outDir, 'plugin-coverage.json')];
const canonical = args.canonicalCoverage
? path.resolve(args.canonicalCoverage)
: path.resolve(outDir, '..', '..', 'discovery', 'plugin-coverage.json');
let canonicalDirExists = Boolean(args.canonicalCoverage);
if (!canonicalDirExists) {
try {
canonicalDirExists = (await fs.stat(path.dirname(canonical))).isDirectory();
} catch {
canonicalDirExists = false;
}
}
if (canonicalDirExists) targets.push(canonical);
for (const target of targets) {
await fs.mkdir(path.dirname(target), { recursive: true });
const tempPath = `${target}.${process.pid}.tmp`;
await fs.writeFile(tempPath, text, 'utf8');
await fs.rename(tempPath, target);
}
return { outcome: 'reclassified', written: targets, cmsFallbackDigest: result.payload.inputs.cmsFallbackDigest };
}
// plugin-rest-child support: a parent-scoped sub-resource (e.g.
// /wc/v3/orders/{parentId}/notes) cannot be listed on its own, so it is checked by
// substituting real ids from the already-sampled parent collection. Pure and exported so the
// id-picking and route-building logic is fixture-testable with no live site.
// Candidate parent ids for a plugin-rest-child entity, drawn from its parent collection's
// already-sampled records and capped at a small representative count — this is a check, not
// an attempt at full coverage.
function pickChildSampleParentIds(parentEntity, limit) {
const records = parentEntity?.sampleRecords || [];
return records
.map((record) => (record && typeof record === 'object' ? record.id : undefined))
.filter((id) => id !== undefined && id !== null)
.slice(0, limit);
}
function buildChildRoutePath(template, parentId) {
return template.replace(CHILD_ROUTE_PLACEHOLDER, encodeURIComponent(String(parentId)));
}
function describeChildSample(sample) {
const label = `${sample.plugin} · ${sample.entity}`;
if (sample.parentsChecked === 0) {
return `${label}: no sampled ${sample.parentRoute} records were available to check ${sample.route} against.`;
}
return `${label}: checked ${sample.parentsChecked} sampled ${sample.parentRoute} record(s)' `
+ `${sample.route} — ${sample.parentsWithRecords} of ${sample.parentsChecked} returned matching records `
+ `(${sample.sampleRecords.length} sample record(s) total). Representative check only, not a full count.`;
}
// Live per-parent sampling for every detected plugin-rest-child entity. Runs after the main
// sampling loop so `sampledByRoute` already holds real parent records to draw ids from.
async function sampleChildEntities({ baseUrl, headers, timeoutMs, sampleLimit, progress, detection, sampledByRoute }) {
const results = [];
const parentSampleLimit = Math.min(3, sampleLimit);
for (const detected of detection?.detected || []) {
for (const entity of detected.entities) {
if (entity.channel !== 'plugin-rest-child' || entity.channelStatus !== 'available') continue;
const parentEntity = sampledByRoute.get(entity.parentRoute);
const parentIds = pickChildSampleParentIds(parentEntity, parentSampleLimit);
if (parentIds.length === 0) {
results.push({
plugin: detected.plugin,
entity: entity.entity,
parentRoute: entity.parentRoute,
route: entity.route,
parentsChecked: 0,
parentsWithRecords: 0,
sampleRecords: [],
});
continue;
}
const sampleRecords = [];
let parentsWithRecords = 0;
for (const parentId of parentIds) {
const childRoute = buildChildRoutePath(entity.route, parentId);
// eslint-disable-next-line no-await-in-loop -- each parent's sub-resource must be
// fetched under the shared rate limiter, one request at a time, like inspectEntity.
const response = await fetchJson(baseUrl, childRoute, {
headers,
method: 'GET',
timeoutMs,
progress,
progressContext: { step: 'sample-child-entity', entity: entity.entity },
});
if (response.ok && Array.isArray(response.json) && response.json.length > 0) {
parentsWithRecords += 1;
sampleRecords.push(...response.json.slice(0, Math.max(0, sampleLimit - sampleRecords.length)));
}
}
results.push({
plugin: detected.plugin,
entity: entity.entity,
parentRoute: entity.parentRoute,
route: entity.route,
parentsChecked: parentIds.length,
parentsWithRecords,
sampleRecords,
});
}
}
return results;
}
// Pure -- no I/O -- so it can be unit-tested directly without mocking httpClient or the
// profile loader. Decides what query a structure-bridge-plugin entity's sample should
// run, or why none can be run at all. `table` is spread in LAST when a fulfillment declares its
// own sampleStructureRequest so a stray `table` key inside that declaration (which
// plugin-knowledge.js's validator already rejects at authoring time) can never silently
// redirect the query at a different table than this entity's fulfillment names -- this is
// the second, independent line of defense for that same invariant.
function resolveSampleStructureRequest(fulfillment, table, schema) {
if (fulfillment.sampleStructureRequest) {
return { sampleRequest: { ...fulfillment.sampleStructureRequest, table }, skippedReason: null };
}
if (schema.columns.length === 0) {
return {
sampleRequest: null,
skippedReason: 'discover-structure returned zero columns for this table -- cannot build a default sample. Unexpected for a real table; the fulfillment metadata or the live schema needs review.',
};
}
if (schema.columns.length > 50) {
return {
sampleRequest: null,
skippedReason: `this table has ${schema.columns.length} columns, more than wix-wp-plugin-v2's own 50-column select limit -- a default "every column" sample would silently drop ${schema.columns.length - 50} of them. This entity's fulfillment must declare an explicit sampleStructureRequest choosing which columns matter; there is no safe default for a table this wide.`,
};
}
// On a key/value table the guarded value column(s) are unreachable until the
// request pins the matching key column, so a default "select every column" sample is a
// request the plugin REFUSES with a 400 -- and a 400 here reads as "this table is broken"
// rather than "this sample was built wrong". Drop the guarded columns and sample the key
// names instead, which is the discovery tier and exactly what a mapper needs first: the
// real key list for whatever plugin this site runs.
const guarded = guardedValueColumns(schema.eavPair);
const sampleable = schema.columns.filter((column) => !guarded.includes(column.name));
if (sampleable.length === 0) {
return {
sampleRequest: null,
skippedReason: 'every column on this table is a guarded key/value column -- nothing can be sampled without naming specific keys first.',
};
}
if (guarded.length > 0) {
return {
sampleRequest: {
table,
select: sampleable.map((column) => ({ column: column.name })),
orderBy: [{ column: schema.eavPair.keyColumn, direction: 'asc' }],
},
skippedReason: null,
eavNote: `key/value table: ${guarded.join(', ')} omitted from this sample because wix-wp-plugin-v2 will not return a value until the request pins its key column (${schema.eavPair.keyColumn}). Read those with a scoped request naming the keys this sample reveals.`,
};
}
const primaryColumn = schema.columns.find((column) => column.key === 'primary') || schema.columns[0];
return {
sampleRequest: {
table,
select: schema.columns.map((column) => ({ column: column.name })),
orderBy: [{ column: primaryColumn.name, direction: 'asc' }],
},
skippedReason: null,
};
}
// Every entity whose blocked[].fulfillment.kind is structure-bridge-plugin has
// no REST route at all -- the ONLY way to capture it is wix-wp-plugin-v2's own routes. Runs
// after plugin detection/coverage so it can skip a plugin that isn't actually active, and
// after the REST sampling passes so it never competes with them for the shared rate limit
// slot ordering. Never throws: a per-entity failure (plugin not installed, table renamed,
// wix-wp-plugin-v2 not installed at all) is recorded as a request error on that entity's own
// file, exactly like an auth-gated REST route already is -- it must not abort discovery.
/**
* Accumulates the per-read counts the client derives and files them with
* rp-telemetry once, at the end of the bridge pass.
*
* Wired HERE, in the real caller, rather than left as a hook nobody calls: `onSourceRead` with
* no production caller is telemetry that exists in the code and not in the data, which is
* indistinguishable from a run that read nothing. Failure to record is swallowed on purpose --
* telemetry must never be able to abort a discovery run, and this whole function is already
* built on "a per-entity failure is recorded, not thrown".
*/
function makeSourceReadCollector(outDir) {
const totals = { discovery_queries: 0, scoped_queries: 0, tier_refusals: 0, redacted_values: 0 };
const discoveryTables = new Set();
const scopedTables = new Set();
return {
onSourceRead(counts) {
for (const key of Object.keys(totals)) totals[key] += counts[key] || 0;
for (const table of counts.discovery_tables || []) discoveryTables.add(table);
for (const table of counts.scoped_tables || []) scopedTables.add(table);
},
countTierRefusal() {
totals.tier_refusals += 1;
},
flush(progress) {
const payload = { ...totals };
if (discoveryTables.size > 0) payload.discovery_tables = [...discoveryTables].sort();
if (scopedTables.size > 0) payload.scoped_tables = [...scopedTables].sort();
if (Object.values(totals).every((n) => n === 0)) return;
try {
// outDir is <project>/discovery/wordpress; the project root is two levels up, the same
// derivation the decisions.json lookup above already uses.
const projectDir = path.resolve(outDir, '..', '..');
// eslint-disable-next-line global-require
require('../../rp-telemetry/lib/telemetry-recorder.js').sourceRead(projectDir, payload);
} catch (error) {
progress?.progress(`source-read telemetry not recorded: ${error.message}`, {
phase: 'discovery',
step: 'structure-bridge-plugin',
});
}
},
};
}
// Source redirect maps, captured completely during discovery (no agent step). A detected
// profile entity with a `redirectSource` block names its provider's bare tables; each is read
// in full through wix-wp-plugin-v2 and handed to wp-redirect-sources' extractor, then persisted
// by the shared recorder into state/url-preservation/. Never throws: no bridge, a missing table
// or a failed page becomes `unreadable` coverage, which can never pass for an empty map; a
// failure to save the rules becomes `not_recorded`.
// Returns null when no redirect provider is detected.
async function readBridgeTableFully({ transport, table }) {
let schema;
try {
schema = await discoverStructure({ httpClient: transport.httpClient, siteBaseUrl: transport.siteBaseUrl, auth: transport.auth, table });
} catch (error) {
return { found: false, read: { error: `discover-structure failed: ${error.message}` } };
}
const { sampleRequest, skippedReason } = resolveSampleStructureRequest({}, table, schema);
if (!sampleRequest || guardedValueColumns(schema.eavPair).length > 0) {
return { found: true, read: { error: skippedReason || 'key/value table: a full read needs named keys' } };
}
const rows = [];
const seenCursors = new Set();
let cursor;
for (;;) {
let page;
try {
page = await queryStructure({ httpClient: transport.httpClient, siteBaseUrl: transport.siteBaseUrl, auth: transport.auth,
structureRequest: sampleRequest, cursor, limit: MAX_PAGE_LIMIT, onSourceRead: transport.onSourceRead });
} catch (error) {
return { found: true, read: { error: `query-structure failed after ${rows.length} row(s): ${error.message}`, complete: false, rows } };
}
rows.push(...page.rows);
const next = page.pagingMetadata.cursors.next;
if (!page.pagingMetadata.hasNext) break;
if (!next || seenCursors.has(next)) return { found: true, read: { error: 'paging did not advance', complete: false, rows } };
seenCursors.add(next);
cursor = next;
}
return { found: true, read: { complete: true, rows } };
}
async function captureSourceRedirects({ baseUrl, headers, namespaces, timeoutMs, progress, detection, outDir,
pluginsDir = null, createTransport = createBridgeTransport, extractedAt = new Date().toISOString(),
recordCapture = (args) => require('../../../lib/source-redirect-capture.js').recordSourceRedirectCapture(args) }) {
const knowledgeDir = pluginsDir || pluginsRoot(path.resolve(__dirname, '..'));
const providers = redirectSources.providersFromProfiles(loadProfiles(knowledgeDir));
const detectedBySlug = new Map((detection?.detected || []).map((entry) => [entry.plugin, entry]));
const active = Object.entries(providers).filter(([, def]) => detectedBySlug.has(def.profile));
if (active.length === 0) return null;
const input = {
extractedAt,
plugins: active.map(([, def]) => ({ slug: def.profile, active: detectedBySlug.get(def.profile).active !== false })),
physicalTables: null,
tables: {},
};
const tables = Array.from(new Set(active.flatMap(([, def]) => def.tables)));
if (tables.length > 0 && (namespaces || []).includes('wix-wp-plugin/v2')) {
const sourceReads = makeSourceReadCollector(outDir);
const transport = createTransport({ baseUrl, headers, timeoutMs, progress, onSourceRead: sourceReads.onSourceRead });
input.physicalTables = [];
for (const table of tables) {
progress?.progress(`Reading redirect table ${table}`, { phase: 'discovery', step: 'source-redirects', entity: table });
const { found, read } = await readBridgeTableFully({ transport, table });
if (found) input.physicalTables.push(table);
input.tables[table] = read;
}
sourceReads.flush(progress);
}
const result = redirectSources.extractRedirectSources(input, { providers: Object.fromEntries(active) });
const projectDir = projectDirOfOutDir(outDir);
let recorded = null;
if (projectDir) {
try {
recorded = await recordCapture({ projectDir, result });
} catch (error) {
// The rules were read but not saved (or their targets not planned): a bad state file or a
// held lock. Discovery goes on; the coverage row says so and asks the Import Operator.
const reason = `rules read but not recorded: ${error.message}`;
result.coverage = { ...result.coverage,
providers: result.coverage.providers.map((p) => ({ ...p, status: 'not_recorded', capturedStatus: p.status, reason })) };
recorded = { error: error.message };
progress?.progress('Source redirect maps not recorded', { phase: 'discovery', step: 'source-redirects', details: { error: error.message } });
}
}
progress?.progress('Source redirect maps captured', {
phase: 'discovery', step: 'source-redirects', count: result.rules.length, unit: 'rules',
details: Object.fromEntries(result.coverage.providers.map((p) => [p.provider, p.status])),
});
return { coverage: result.coverage, rules: result.rules.length, recorded };
}
// Annotate plugin coverage with a redirect capture and rebuild the views derived from rows.
function withRedirectCapture(plugins, captureCoverage, { pluginsDir = null } = {}) {
if (!plugins || !captureCoverage) return plugins;
const knowledgeDir = pluginsDir || pluginsRoot(path.resolve(__dirname, '..'));
const coverage = redirectSources.annotateRedirectCoverageRows(plugins.coverage, captureCoverage,
{ providers: redirectSources.providersFromProfiles(loadProfiles(knowledgeDir)) });
const disposition = buildDispositionRows({ detection: plugins.detection, coverage, profiles: loadProfiles(knowledgeDir), hints: loadNoMigrationNeeded(knowledgeDir) });
return { ...plugins, coverage, summary: coverageSummary(coverage), disposition, dispositionSummary: summarizeDispositions(disposition) };
}
// The latest recorded capture for a project, or null.
function readRecordedRedirectCoverage(projectDir) {
if (!projectDir) return null;
try {
return JSON.parse(require('node:fs').readFileSync(path.join(projectDir, 'state', 'url-preservation', 'source-redirect-coverage.json'), 'utf8'));
} catch {
return null;
}
}
// The one wix-wp-plugin-v2 bridge transport: discovery samples and the pre-checkpoint full
// read (plugin-full-read.js) use the same credential selection and HTTP client.
function createBridgeTransport({ baseUrl, headers, timeoutMs, progress, onSourceRead }) {
const httpClient = {
async get(url, { params } = {}) {
const response = await fetchJson(baseUrl, '/wix-wp-plugin/v2/structure', {
headers, method: 'GET', query: params, timeoutMs, progress,
progressContext: { step: 'structure-bridge-discover', entity: params?.table },
});
if (!response.ok) {
const error = new Error(`HTTP ${response.status} ${response.statusText}`);
error.status = response.status;
throw error;
}
return { data: response.json };
},
async post(url, { body } = {}) {
const response = await fetchJson(baseUrl, '/wix-wp-plugin/v2/query/admin-key', {
headers, method: 'POST', body, timeoutMs, progress,
progressContext: { step: 'structure-bridge-query' },
});
if (!response.ok) {
const error = new Error(`HTTP ${response.status} ${response.statusText}`);
error.status = response.status;
throw error;
}
return { data: response.json };
},
};
return { httpClient, siteBaseUrl: baseUrl, auth: undefined, structureMethod: 'GET', queryRoute: '/wix-wp-plugin/v2/query/admin-key', onSourceRead };
}
async function sampleStructureBridgeEntities({ baseUrl, headers, namespaces, sampleLimit, timeoutMs, progress, detection, outDir }) {
if (!namespaces.includes('wix-wp-plugin/v2')) {
progress?.progress('wix-wp-plugin-v2 not detected on this site; skipping structure-bridge-plugin entities', {
phase: 'discovery',
step: 'structure-bridge-plugin',
});
return [];
}
const bridge = createBridgeTransport({ baseUrl, headers, timeoutMs, progress });
const { httpClient, auth: bridgeAuth, structureMethod: bridgeStructureMethod, queryRoute: bridgeQueryRoute } = bridge;
const detectedSlugs = new Set((detection?.detected || []).map((entry) => entry.plugin));
const profiles = loadProfiles(pluginsRoot(path.resolve(__dirname, '..')));
const results = [];
const sourceReads = makeSourceReadCollector(outDir);
for (const profile of profiles) {
if (!detectedSlugs.has(profile.plugin)) continue;
for (const entity of profile.entities || []) {
const blockedEntries = [
...(entity.blocked || []),
...((entity.pitfalls || []).flatMap((pitfall) => pitfall.blocked || [])),
];
for (const blockedEntry of blockedEntries) {
const fulfillment = blockedEntry.fulfillment;
if (!fulfillment || fulfillment.kind !== 'structure-bridge-plugin' || fulfillment.handlerId !== 'wix-wp-plugin-v2') continue;
const { table } = fulfillment;
const fileName = `${slugify('wix-wp-plugin/v2')}--${slugify(table)}.md`;
const notes = [
`Captured via wix-wp-plugin-v2's discover-structure (schema) and query-structure (sample rows), not the WordPress REST API -- this entity has no REST route at all (channel: ${entity.channel}).`,
`Source plugin: ${profile.plugin}.`,
];
const requestErrors = [];
let schema = null;
let sampleRecords = [];
let recordCount = null;
progress?.progress(`Inspecting structure-bridge-plugin table ${table}`, {
phase: 'discovery',
step: 'structure-bridge-plugin',
entity: table,
});
try {
schema = await discoverStructure({ httpClient, siteBaseUrl: baseUrl, auth: bridgeAuth, table });
} catch (error) {
const forbiddenCode = bridgeForbiddenCode(error.status, namespaces);
requestErrors.push({
request: bridgeStructureMethod, routePath: `/wix-wp-plugin/v2/structure?table=${table}`, status: error.status || 0, statusText: error.message,
...(forbiddenCode ? { code: forbiddenCode } : {}),
});
notes.push(forbiddenCode
? `discover-structure failed: ${error.message}. ${forbiddenCode}: this site has no WooCommerce, and a wix-wp-plugin-v2 copy older than 0.5.0 admits only manage_woocommerce. Ask the site owner to upload the current wix-wp-plugin-v2 zip (0.5.0+, which also admits an administrator), then run discovery again. If the plugin is already 0.5.0+, the Application Password user is not an administrator.`
: `discover-structure failed: ${error.message}. wix-wp-plugin-v2 may not be fully installed/authorized on this site, or ${table} may not exist -- this entity's fulfillment metadata may need review.`);
results.push({
entityName: entity.entity, namespace: 'wix-wp-plugin/v2', routePath: `/structure?table=${table}`,
classification: null, methods: ['GET'], responseShape: 'object', recordCount: null, inUse: null,
sampleRecords: [], discoveryNotes: notes, relationships: [], requestErrors, schema: null, collectionArgs: [], fileName,
});
continue;
}
// The authoritative `table` is spread LAST so it always wins even if a declared
// sampleStructureRequest carried its own `table` key -- plugin-knowledge.js's
// validator already rejects that key at authoring time, but this ordering is the
// second, independent line of defense: a profile can never make this code query a
// different table than the one this entity's filename/notes say it describes.
const { sampleRequest, skippedReason: sampleSkippedReason, eavNote } = resolveSampleStructureRequest(fulfillment, table, schema);
// Surfaced to the mapper, not swallowed: "this table's values need a second, scoped
// read" is exactly the kind of thing that turns into a silent data gap if the sample
// merely looks a bit thin.
if (eavNote) notes.push(eavNote);
if (fulfillment.sampleStructureRequest) {
notes.push('This sample uses the fulfillment\'s own declared query, not a raw "select every column" dump -- see this entity\'s blocked[].resolution for why a raw sample is not safe here.');
}
let queried = false;
if (sampleSkippedReason) {
notes.push(sampleSkippedReason);
} else {
try {
const response = await queryStructure({
httpClient, siteBaseUrl: baseUrl, auth: bridgeAuth, structureRequest: sampleRequest, limit: sampleLimit,
onSourceRead: sourceReads.onSourceRead,
});
sampleRecords = response.rows;
recordCount = response.pagingMetadata.total;
queried = true;
// A redaction is a finding about the SOURCE SITE -- it means a credential is
// stored somewhere nobody expected -- so it belongs in the discovery record
// rather than being noticed later as a value that looks oddly literal.
if (response.redactionMetadata.redactedValueCount > 0) {
notes.push(`${response.redactionMetadata.redactedValueCount} value(s) in ${response.redactionMetadata.redactedColumns.join(', ')} matched a credential shape and were returned as [REDACTED:secret-shaped]. This is a source-site finding, not a sampling error: something on this site keeps a secret in this column.`);
}
if (response.eavAccess) {
notes.push(`Key/value table, served in the ${response.eavAccess.tier} tier: key column ${response.eavAccess.keyColumn}, guarded value column(s) ${guardedValueColumns(response.eavAccess).join(', ')}.`);
}
} catch (error) {
requestErrors.push({ request: 'POST', routePath: bridgeQueryRoute, status: error.status || 0, statusText: error.message });
notes.push(`query-structure failed: ${error.message}. Schema above is still real; no sample rows could be captured this run.`);
// Count a tier refusal only when the REQUEST actually violates the tier rule.
// A 400 here can equally mean a nonexistent column (an outdated profile naming a
// column the site dropped), a malformed request, or a bad cursor -- the plugin
// uses one error for all of them on purpose, so that a refusal never discloses
// which column holds values. Deciding from the request instead keeps
// `tier_refusals` meaning "something tried to reach values it had not named".
if (error.status === 400 && violatesTierRule(sampleRequest, schema.eavPair)) {
sourceReads.countTierRefusal();
}
}
}
// Persisted as a machine-readable sidecar (not just described in this file's own
// "Collection Args" prose) so rp-import-codegen can consume the EXACT request
// verbatim instead of re-deriving its own default at codegen time, which could
// drift from this one if the table's live schema changes in between (this is a normal reader,
// not a blocked-dependency snapshot). This filename is
// computed unconditionally (even when nothing gets written this run) so writeOutputs
// can clean up a STALE sidecar from a prior run when this run could not produce a
// fresh one -- publishing only happens when the query actually succeeded (`queried`),
// never merely because a request was built; a failed or skipped run must not leave a
// sidecar codegen would then trust as current.
const structureRequestArtifactFileName = `${slugify('wix-wp-plugin/v2')}--${slugify(table)}.structure-request.json`;
const structureRequestArtifact = queried
? { fileName: structureRequestArtifactFileName, content: sampleRequest }
: null;
// A key/value table needs a SECOND artifact, because the request above deliberately
// omits the guarded value columns -- a reader running it verbatim extracts key names
// and no values, which is the opposite of what this capability is for. The read plan
// is the executable second step: every distinct key, batched at the plugin's 50-key
// cap, each batch a complete runnable request.
const eavReadPlanFileName = `${slugify('wix-wp-plugin/v2')}--${slugify(table)}.eav-read-plan.json`;
let eavReadPlan = null;
// Deliberately NOT gated on `queried`. The ordinary sample is skipped for a table wider
// than the 50-column select cap (and fails for other reasons too), but key discovery
// selects exactly ONE column, so nothing that stopped the sample applies to it. Tying
// the two together meant a wide key/value table -- which a busy `postmeta` absolutely
// can be -- silently lost its only path to values.
if (schema.eavPair) {
try {
const pairs = [
{ keyColumn: schema.eavPair.keyColumn, valueColumn: schema.eavPair.valueColumn },
...(schema.eavPair.additionalPairs || []),
];
// One key sweep PER PAIR: each value column answers only to its own key column, so
// one pair's key list cannot unlock another pair's values.
const keysByPair = {};
const countsByPair = {};
let anyTruncated = false;
let totalPages = 0;
for (const pair of pairs) {
// eslint-disable-next-line no-await-in-loop
const discovered = await discoverEavKeys({
httpClient, siteBaseUrl: baseUrl, auth: bridgeAuth, table, keyColumn: pair.keyColumn,
onSourceRead: sourceReads.onSourceRead,
});
keysByPair[pair.keyColumn] = discovered.keys;
countsByPair[pair.keyColumn] = discovered.keyCounts;
anyTruncated = anyTruncated || discovered.truncated;
totalPages += discovered.pages;
}
const content = buildEavReadPlan({
table, eavPair: schema.eavPair, schemaColumns: schema.columns, keysByPair, countsByPair, truncated: anyTruncated,
});
eavReadPlan = { fileName: eavReadPlanFileName, content };
notes.push(
`Key/value table: ${content.distinctKeyCount} distinct key(s) across ${pairs.length} pair(s), discovered over ${totalPages} page(s). `
+ `Values are extracted by ${content.expectedBatches} scoped batch(es)`
+ (content.expectedScopedRequests === null ? '' : ` (~${content.expectedScopedRequests} paginated request(s))`)
+ ` carrying ${content.identityColumns.join(', ') || 'no'} identity column(s) -- `
+ `see ${eavReadPlanFileName}, which rp-import-codegen runs verbatim.`
+ (anyTruncated ? ' *** KEY LIST TRUNCATED: this extraction cannot be treated as whole-table. ***' : '')
+ (content.droppedIdentityColumns.length === 0 ? ''
: ` *** WIDER THAN THE 50-COLUMN SELECT CAP: ${content.droppedIdentityColumns.length} column(s) are absent from every extracted row (${content.droppedIdentityColumns.join(', ')}). `
+ 'Every row will be INCOMPLETE per record until the mapping narrows this table and the plan is regenerated with an explicit column choice. ***')
+ (content.orderByIsUnique ? '' : ` *** No primary or NOT-NULL unique column: batches order by ${content.orderColumn}, which can tie, so paging is best-effort. ***`),
);
} catch (error) {
// Never fatal: the schema above is still real, and a discovery run must not abort
// because one table's key sweep failed.
notes.push(`Key discovery for the scoped-value read failed: ${error.message}. Values for this table cannot be extracted until this succeeds.`);
requestErrors.push({ request: 'POST', routePath: bridgeQueryRoute, status: error.status || 0, statusText: error.message });
}
}
results.push({
entityName: entity.entity,
sourceEntityRef: `plugin.${profile.plugin}.${entity.entity}`,
sourceMeta: { plugin: profile.plugin, candidateTargetRefs: entity.candidateTargetRefs || [] },
namespace: 'wix-wp-plugin/v2',
routePath: `/query/admin-key (table=${table})`,
classification: null,
methods: ['POST'],
responseShape: 'object',
recordCount,
inUse: sampleRecords.length > 0,
sampleRecords,
discoveryNotes: notes,
relationships: [],
requestErrors,
schema,
// Not literally REST "collection args" (no such concept here) -- reusing this
// section to display the actual structureRequest this sample used (or an empty
// array when none was attempted), so a human reader can see (e.g.) that
// gift-card-activity's sample is an aggregate query, not a raw dump, without
// having to go read the plugin profile's JSON. The machine-readable copy
// consumers should actually parse is structureRequestArtifact below.
collectionArgs: sampleRequest ? [sampleRequest] : [],
fileName,
structureRequestArtifact,
structureRequestArtifactFileName,
eavReadPlan,
eavReadPlanFileName,
});
}
}
}
// One telemetry write for the whole bridge pass, after every entity, so a resumed or
// partially-failed run still files what it actually read.
sourceReads.flush(progress);
return results;
}
// Everything this run advertised or attempted but did not capture as an entity
// (401/403, failed capture, a data route skipped by rule, an unsupported route surface). Always
// written, `rows: []` when there is nothing to report; rp-discovery refuses to promote without it.
function sourceCoveragePayload(context) {
return buildCoverageFile({
platform: 'wordpress',
adapter: 'wordpress',
generatedAt: context.generatedAt,
rows: buildWordPressCoverageRows({
entities: context.entities,
classifications: context.classifications,
rawDir: ADAPTER_RAW_DIRS.wordpress,
}),
});
}
function pluginCoveragePayload(context) {
const plugins = context.plugins;
return {
generatedAt: context.generatedAt,
baseUrl: context.baseUrl,
authenticated: context.authMode !== 'none',
bridgeAuthMode: context.bridgeAuthMode,
pluginListAvailable: plugins.detection.pluginListAvailable,
notes: [
...(context.pluginNotes || []),
...(plugins.targetKnowledgeError
? [`Wix target knowledge could not be loaded (${plugins.targetKnowledgeError}); target refs were not resolved.`]
: []),
...(plugins.childSamples || []).map(describeChildSample),
],
childSamples: plugins.childSamples || [],
summary: plugins.summary,
perPluginSummary: plugins.dispositionSummary,
// The status invariant: N installed plugins produce N per-plugin rows, recognized or not.
// Recorded here so the check is inspectable in the artifact, not just in tests.
statusInvariant: {
detectedRecognized: plugins.detection.detected.length,
installedButUnrecognized: plugins.detection.installedButUnprofiled.length,
genericEntities: plugins.genericEntities.length,
unprofiledNamespaces: plugins.unprofiled.length,
pluginListAvailable: plugins.detection.pluginListAvailable,
// This skill's own plugins (no-migration-needed.json toolkitPlugins[]): installed, not listed.
toolkitExcluded: plugins.toolkitExcluded || 0,
},
capabilities: plugins.coverage,
// One artifact, two views: the capability rows above are the contract;
// this per-plugin projection answers the question a merchant actually asks.
perPlugin: plugins.disposition,
genericEntities: plugins.genericEntities,
bridgeEntities: plugins.bridgeEntities || [],
unprofiledRoutes: plugins.unprofiled,
// Durable per-route counts and sample evidence, so --reclassify-coverage never refetches.
entityStats: plugins.entityStats || {},
// raw dataPresence observations, so --reclassify-coverage reuses them.
dataPresence: plugins.dataPresenceObservations || [],
// Malformed pluginCmsFallback:* answers with no capability row to carry them.
cmsFallbackDecisionIssues: plugins.cmsFallbackDecisionIssues || [],
// The CMS-fallback resolution-input digest. rp-mapper copies it into mapping-plan.json and
// rp-setup-discovery into setup-plan.json; the router refuses any artifact that disagrees.
inputs: { cmsFallbackDigest: plugins.cmsFallbackDigest || null },
};
}
async function ensureDir(dirPath) {
await fs.mkdir(dirPath, { recursive: true });
}
async function writeOutputs(outDir, context, progress) {
await ensureDir(outDir);
const planProjectDir = context.projectDir ? path.resolve(context.projectDir)
: (path.basename(path.resolve(outDir)) === 'wp-discovery' && path.basename(path.dirname(path.resolve(outDir))) === 'data' ? path.resolve(outDir, '../..') : null);
if (planProjectDir) {
const { sha } = require('../lib/plugin-entity-read-plan.js');
for (const entity of context.entities) {
if (entity.sourceEntityRef && entity.namespace === 'wix-wp-plugin/v2') {
entity.fileName = `wix-wp-plugin-v2--${sha(entity.sourceEntityRef)}.md`;
entity.rawFile = entity.fileName;
}
}
}
await fs.writeFile(path.join(outDir, 'README.md'), renderIndexFile(context), 'utf8');
progress?.progress('Wrote WordPress discovery index', { phase: 'discovery', step: 'write-artifact', artifact: path.join(outDir, 'README.md') });
await fs.writeFile(
path.join(outDir, 'skipped-routes.json'),
`${JSON.stringify(skippedRoutesPayload(context), null, 2)}\n`,
'utf8',
);
progress?.progress('Wrote WordPress skipped-route index', {
phase: 'discovery',
step: 'write-artifact',
artifact: path.join(outDir, 'skipped-routes.json'),
});
await fs.writeFile(
path.join(outDir, 'source-coverage.json'),
`${JSON.stringify(sourceCoveragePayload(context), null, 2)}\n`,
'utf8',
);
progress?.progress('Wrote WordPress source coverage', {
phase: 'discovery',
step: 'write-artifact',
artifact: path.join(outDir, 'source-coverage.json'),
});
if (context.plugins) {
await fs.writeFile(
path.join(outDir, 'plugin-inventory.json'),
`${JSON.stringify(inventoryPayload({
generatedAt: context.generatedAt,
baseUrl: context.baseUrl,
authenticated: context.authMode !== 'none',
detection: context.plugins.detection,
notes: context.pluginNotes || [],
unprofiled: context.plugins.unprofiled,
profileCount: context.pluginProfileCount,
}), null, 2)}\n`,
'utf8',
);
progress?.progress('Wrote WordPress plugin inventory', {
phase: 'discovery',
step: 'write-artifact',
artifact: path.join(outDir, 'plugin-inventory.json'),
});
await fs.writeFile(
path.join(outDir, 'plugin-coverage.json'),
`${JSON.stringify(pluginCoveragePayload(context), null, 2)}\n`,
'utf8',
);
progress?.progress('Wrote WordPress plugin coverage', {
phase: 'discovery',
step: 'write-artifact',
artifact: path.join(outDir, 'plugin-coverage.json'),
});
// Deliberately no plugin-disposition.md: the per-plugin view lives inside
// plugin-coverage.json (one coverage artifact, no second document).
}
for (const entity of context.entities) {
if (entity.sourceEntityRef && entity.namespace === 'wix-wp-plugin/v2'
&& planProjectDir) {
const plans = require('../lib/plugin-entity-read-plan.js');
const projectDir = planProjectDir;
try {
const artifact = entity.eavReadPlan || entity.structureRequestArtifact;
if (!artifact || !entity.schema) throw Object.assign(new Error('discovery could not produce a supported read recipe; inspect its storage evidence'), { code: 'plan-unavailable' });
const base = `data/wp-discovery/entity-read-plans/${plans.sha(entity.sourceEntityRef)}`;
const evidence = plans.writeJson(projectDir, `${base}/schema.json`, entity.schema);
const request = plans.writeJson(projectDir, `${base}/${entity.eavReadPlan ? 'eav-read-plan' : 'structure-request'}.json`, artifact.content);
plans.writePluginEntityReadPlan({ projectDir, siteBaseUrl: context.baseUrl, sourceEntity: entity,
plan: { schemaVersion: 1, sourceEntityRef: entity.sourceEntityRef, sourceIdentity: plans.sourceIdentity(context.baseUrl), evidenceRefs: [evidence],
components: [{ id: 'root', table: entity.schema.table, variant: entity.eavReadPlan ? 'eav' : 'single-request', schema: entity.schema,
readArtifacts: { [entity.eavReadPlan ? 'eavReadPlan' : 'structureRequest']: request }, scope: { where: artifact.content.where || [] } }],
assembly: { kind: 'identity', identityColumn: artifact.content.groupBy?.[0] || entity.schema.columns.find((column) => column.key === 'primary' || (column.key === 'unique' && column.nullable === false))?.name || '' },
cost: { expectedRequests: artifact.content.expectedScopedRequests ?? null } } });
} catch (error) {
plans.invalidatePluginEntityReadPlan({ projectDir, sourceEntityRef: entity.sourceEntityRef });
entity.sourceMeta = { ...entity.sourceMeta, extractionPlan: null };
plans.recordPluginExtractionDeferral({ projectDir, sourceEntityRef: entity.sourceEntityRef, code: error.code || 'plan-invalid', reason: error.message, producer: 'rp-source-wordpress/scripts/wp-discovery.js' });
entity.discoveryNotes.push(`Entity plan deferred: ${error.message}`);
}
}
const metadata = entity.sourceEntityRef ? `\n## Source binding\n\n${JSON.stringify({ sourceEntityRef: entity.sourceEntityRef, bridgeDesignated: true, sourceMeta: entity.sourceMeta }, null, 2)}\n` : '';
await fs.writeFile(path.join(outDir, entity.fileName), renderEntityFile(entity) + metadata, 'utf8');
progress?.progress(`Wrote WordPress discovery artifact for ${entity.entityName}`, {
phase: 'discovery',
step: 'write-artifact',
entity: entity.routePath,
artifact: path.join(outDir, entity.fileName),
});
// structure-bridge-plugin entities additionally persist the exact
// structureRequest their sample used, as machine-readable JSON alongside the
// human-readable markdown -- see sampleStructureBridgeEntities()'s own comment on why.
if (entity.structureRequestArtifact) {
const artifactPath = path.join(outDir, entity.structureRequestArtifact.fileName);
await fs.writeFile(artifactPath, `${JSON.stringify(entity.structureRequestArtifact.content, null, 2)}\n`, 'utf8');
progress?.progress(`Wrote structure-request artifact for ${entity.entityName}`, {
phase: 'discovery',
step: 'write-artifact',
entity: entity.routePath,
artifact: artifactPath,
});
} else if (entity.structureRequestArtifactFileName) {
// This run could not produce a fresh sidecar (query skipped or failed) -- delete any
// sidecar a PRIOR run left behind for this exact table, so rp-import-codegen can never
// consume a stale one and mistake it for this run's (non-existent) authoritative query.
const stalePath = path.join(outDir, entity.structureRequestArtifactFileName);
try {
await fs.unlink(stalePath);
progress?.progress(`Removed stale structure-request artifact for ${entity.entityName}`, {
phase: 'discovery',
step: 'write-artifact',
entity: entity.routePath,
artifact: stalePath,
});
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
// Same publish-or-clean rule for the scoped-value read plan: a stale plan is worse than a
// missing one, because codegen would run it and produce a confidently wrong extraction
// against a key list the site no longer has.
if (entity.eavReadPlan) {
const planPath = path.join(outDir, entity.eavReadPlan.fileName);
await fs.writeFile(planPath, `${JSON.stringify(entity.eavReadPlan.content, null, 2)}\n`, 'utf8');
progress?.progress(`Wrote EAV read plan for ${entity.entityName}`, {
phase: 'discovery',
step: 'write-artifact',
entity: entity.routePath,
artifact: planPath,
});
} else if (entity.eavReadPlanFileName) {
try {
await fs.unlink(path.join(outDir, entity.eavReadPlanFileName));
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
}
}
// The store's currency, time zone, language and country, written next to the coverage file for
// promotion. Reads are bounded (two GETs, or one when the store-settings capture already ran)
// and a denied or failed read is an explicit unknown in the file, never a discovery failure.
// Only the standard `<project>/data/wp-discovery` layout can be promoted, so any other --out-dir
// is skipped with a note.
async function captureSourceRegional({ outDir, baseUrl, headers, timeoutMs, entities, generatedAt, progress: log = null, fetch = fetchJson }) {
const resolved = path.resolve(outDir);
const projectDir = path.resolve(resolved, '..', '..');
if (resolved !== path.join(projectDir, ADAPTER_RAW_DIRS.wordpress)) {
log?.progress('Skipped source regional capture: --out-dir is not <project>/data/wp-discovery', { phase: 'discovery', step: 'regional-settings' });
return null;
}
let capturedGeneral = null;
try {
capturedGeneral = JSON.parse(await fs.readFile(path.join(projectDir, 'data', 'store-settings-general.json'), 'utf8'));
} catch { /* not captured (or unreadable): read the route instead */ }
const settings = await regionalCapture.readRegionalSettings({ baseUrl, headers, fetchJson: fetch, timeoutMs, progress: log, capturedGeneral });
const file = regionalCapture.buildWordPressRegional({
...settings,
ordersEntity: entities.find((entity) => entity.routePath === regionalCapture.ORDERS_ROUTE) || null,
generatedAt,
});
const target = await writeAdapterSourceRegional(projectDir, 'wordpress', file);
log?.progress('Wrote WordPress source regional file', { phase: 'discovery', step: 'write-artifact', artifact: target });
return file;
}
async function main() {
const parsed = parseProgressArgs(process.argv.slice(2));
progress = createProgressLogger({
script: 'skills/wix-replatform/resources/rp-source-wordpress/scripts/wp-discovery.js',
...parsed.progress,
});
progress.start('WordPress discovery started', { phase: 'discovery' });
const args = await hydrateArgsFromEnvFile(parseArgs(parsed.args));
if (args.help) {
printUsage();
progress.complete('WordPress discovery help shown', { phase: 'discovery', step: 'help' });
return;
}
if (args.reclassifyCoverage) {
const result = await runReclassifyCoverage(args);
console.log(JSON.stringify({ ok: result.outcome === 'reclassified', ...result }, null, 2));
if (result.outcome !== 'reclassified') {
progress.warn('Plugin coverage reclassification needs a full discovery run', { phase: 'discovery', step: 'reclassify-coverage' });
process.exitCode = 3;
return;
}
progress.complete('Plugin coverage reclassified without refetching', { phase: 'discovery', step: 'reclassify-coverage' });
return;
}
if (!args.baseUrl || !args.outDir) {
printUsage();
progress.error('Missing required WordPress discovery arguments', { phase: 'discovery' });
throw new Error('Missing required arguments: --base-url and --out-dir are required.');
}
configureRateLimit({ rateLimitRpm: args.rateLimitRpm, maxRetries: args.maxRetries });
const headers = buildHeaders(args);
const rootResponse = await fetchJson(args.baseUrl, '', {
headers,
method: 'GET',
timeoutMs: args.timeoutMs,
progress,
progressContext: { step: 'rest-index' },
});
if (!rootResponse.ok || !rootResponse.json) {
throw new Error(`Failed to fetch WordPress REST index from ${rootResponse.url}: ${rootResponse.status} ${rootResponse.statusText}`);
}
const indexJson = rootResponse.json;
const namespaces = Array.isArray(indexJson?.namespaces) ? indexJson.namespaces : [];
progress.progress('WordPress namespace enumeration completed', {
phase: 'discovery',
step: 'namespace-enumeration',
count: namespaces.length,
unit: 'namespaces',
});
// Plugin inventory pre-pass: runs before classification so profile-declared routes are
// already in scope when routes are classified.
let inventory = null;
if (args.pluginInventory) {
try {
const gathered = await gatherInventory({
baseUrl: args.baseUrl,
headers,
timeoutMs: args.timeoutMs,
htmlFingerprint: args.htmlFingerprint,
restIndex: indexJson,
logger: progress,
});
inventory = gathered;
progress.progress('WordPress plugin inventory completed', {
phase: 'discovery',
step: 'plugin-inventory',
count: gathered.detection.detected.length,
unit: 'plugins',
details: {
pluginListAvailable: gathered.detection.pluginListAvailable,
installedButUnprofiled: gathered.detection.installedButUnprofiled.length,
},
});
} catch (error) {
// Never fail discovery over the plugin pre-pass; record and continue.
progress.progress(`WordPress plugin inventory skipped: ${error.message}`, {
phase: 'discovery',
step: 'plugin-inventory',
});
}
}
const requestOverrides = buildRequestOverrides(pluginsRoot(path.resolve(__dirname, '..')));
const candidates = deriveEntityCandidates(indexJson, args.includeNamespaces, requestOverrides);
progress.progress('WordPress endpoint candidates derived', {
phase: 'discovery',
step: 'derive-endpoints',
count: candidates.length,
unit: 'endpoints',
});
// Registered post types/taxonomies are positive evidence for classification, so the
// inventory pre-pass must run before this point (it fetches /wp/v2/types+taxonomies).
const classifications = classifyRoutes(candidates, {
...summarizeOverrides(args),
registeredRestBases: inventory ? buildRegisteredRestBases({ types: inventory.types, taxonomies: inventory.taxonomies }) : null,
});
// classifyRoutes() loads the checked-in plugin profiles lazily via defaultPluginRules();
// a failed load degrades to zero plugin rules with no exception, so it must be surfaced
// here or every plugin-owned route silently falls through to generic/unsupported handling.
const pluginRulesError = defaultPluginRules().loadError || null;
if (pluginRulesError) {
progress.progress(`WordPress plugin route rules could not be loaded (${pluginRulesError}); plugin-owned routes will not be recognized this run.`, {
phase: 'discovery',
step: 'classify-endpoints',
});
}
const candidatesByRoute = new Map(candidates.map((candidate) => [candidate.routePath, candidate]));
const candidatesToInspect = classifications
.filter((classification) => ['sample', 'metadata'].includes(classification.effectiveAction))
.map((classification) => ({
...candidatesByRoute.get(classification.routePath),
classification,
}));
const skippedByCategory = summarizeSkippedByCategory(classifications);
const skippedRoutes = classifications.filter((classification) => classification.effectiveAction === 'skip').length;
progress.progress('WordPress endpoint candidates classified', {
phase: 'discovery',
step: 'classify-endpoints',
count: candidatesToInspect.length,
total: candidates.length,
unit: 'endpoints',
details: {
sampledRoutes: candidatesToInspect.length,
skippedRoutes,
skippedByCategory,
},
});
const entities = [];
const responseEnvelopes = buildResponseEnvelopes(pluginsRoot(path.resolve(__dirname, '..')));
const responseFragmentGroups = buildResponseFragmentGroups(pluginsRoot(path.resolve(__dirname, '..')));
const recordKeyFields = buildRecordKeyFields(pluginsRoot(path.resolve(__dirname, '..')));
for (let i = 0; i < candidatesToInspect.length; i += 1) {
const candidate = candidatesToInspect[i];
progress.progress(`Inspecting WordPress endpoint ${candidate.routePath}`, {
phase: 'discovery',
step: 'inspect-endpoint',
entity: candidate.routePath,
count: i + 1,
total: candidatesToInspect.length,
unit: 'endpoints',
percent: candidatesToInspect.length ? Math.round(((i + 1) / candidatesToInspect.length) * 100) : 100,
});
const details = await inspectEntity(args.baseUrl, headers, candidate, {
sampleLimit: args.sampleLimit,
timeoutMs: args.timeoutMs,
progress,
responseEnvelope: responseEnvelopes.get(candidate.routePath) || null,
responseFragmentGroupSize: responseFragmentGroups.get(candidate.routePath) || null,
recordKeyField: recordKeyFields.get(candidate.routePath) || null,
requestOverride: candidate.requestOverride,
defaultQuery: defaultQueryFor(candidate.routePath),
defaultQueryReason: defaultQueryReasonFor(candidate.routePath),
});
entities.push(details);
}
// Second detection pass + Tier-B derivation + coverage. This is where plugins that add
// no REST route (Product Bundles, ACF, Yoast) become visible, because it looks at the
// record payload keys the sampling loop just collected.
let plugins = null;
if (inventory) {
plugins = buildPluginCoverage({ args, inventory, classifications, entities, allCandidates: candidates });
if (plugins.profiles.some((profile) => profile.dataPresence
&& plugins.detection.detected.some((detected) => detected.plugin === profile.plugin))) {
const dataPresenceObservations = await collectDataPresence({
args, headers, namespaces, profiles: plugins.profiles, detection: plugins.detection,
});
plugins = buildPluginCoverage({ args, inventory, classifications, entities, allCandidates: candidates, dataPresenceObservations });
}
progress.progress('WordPress plugin coverage classified', {
phase: 'discovery',
step: 'plugin-coverage',
count: plugins.coverage.length,
unit: 'capabilities',
details: plugins.summary.byStatus,
});
// Third pass: plugin-rest-child entities — a parent-scoped sub-resource
// (e.g. /wc/v3/orders/{parentId}/notes) cannot be listed on its own, so it is checked by
// substituting real ids from the parent collection this run already sampled.
const childSamples = await sampleChildEntities({
baseUrl: args.baseUrl,
headers,
timeoutMs: args.timeoutMs,
sampleLimit: args.sampleLimit,
progress,
detection: plugins.detection,
sampledByRoute: new Map(entities.map((entity) => [entity.routePath, entity])),
});
if (childSamples.length > 0) {
progress.progress('WordPress per-parent sub-resource sampling completed', {
phase: 'discovery',
step: 'sample-child-entity',
count: childSamples.length,
unit: 'entities',
});
}
plugins = { ...plugins, childSamples };
// Fourth pass: structure-bridge-plugin entities -- data with no REST route
// at all, captured through wix-wp-plugin-v2 instead. Pushed into the same `entities`
// array so it flows through the existing per-entity markdown writer unchanged; run
// after detection/coverage so it can skip a plugin that isn't actually active.
const structureBridgeEntities = await sampleStructureBridgeEntities({
baseUrl: args.baseUrl,
headers,
namespaces,
sampleLimit: args.sampleLimit,
timeoutMs: args.timeoutMs,
progress,
detection: plugins.detection,
outDir: args.outDir,
});
if (structureBridgeEntities.length > 0) {
progress.progress('wix-wp-plugin-v2 structure-bridge-plugin capture completed', {
phase: 'discovery',
step: 'structure-bridge-plugin',
count: structureBridgeEntities.length,
unit: 'entities',
});
}
entities.push(...structureBridgeEntities);
// Fifth pass: source redirect maps (redirect plugins' own tables), read in full.
let redirectCapture = null;
try {
redirectCapture = await captureSourceRedirects({
baseUrl: args.baseUrl,
headers,
namespaces,
timeoutMs: args.timeoutMs,
progress,
detection: plugins.detection,
outDir: args.outDir,
pluginsDir: args.pluginsRoot ? path.resolve(args.pluginsRoot) : null,
});
} catch (error) {
// Never fail discovery over the redirect pass; the redirect row keeps its read blocker.
progress.progress('Source redirect capture failed', { phase: 'discovery', step: 'source-redirects', details: { error: error.message } });
}
if (redirectCapture) plugins = withRedirectCapture(plugins, redirectCapture.coverage, { pluginsDir: args.pluginsRoot ? path.resolve(args.pluginsRoot) : null });
}
const context = {
generatedAt: new Date().toISOString(),
baseUrl: normalizeBaseUrl(args.baseUrl),
restRoot: `${normalizeBaseUrl(args.baseUrl)}/wp-json`,
authMode: summarizeAuthMode(args),
bridgeAuthMode: summarizeBridgeAuthMode(args),
authProviders: Object.keys(indexJson?.authentication || {}),
namespaces,
totalAdvertisedRoutes: Object.keys(indexJson?.routes || {}).length,
totalCandidateRoutes: candidates.length,
sampledRoutes: candidatesToInspect.length,
skippedRoutes,
skippedByCategory,
overrides: summarizeOverrides(args),
classifications,
routeIndexSample: Object.keys(indexJson?.routes || {}).slice(0, 50),
entities,
plugins,
pluginNotes: [
...(inventory ? inventory.notes : ['Plugin inventory was disabled with --no-plugin-inventory.']),
...(pluginRulesError
? [`WordPress plugin route rules could not be loaded (${pluginRulesError}); plugin-owned routes were not recognized this run.`]
: []),
],
pluginProfileCount: inventory ? inventory.profileCount : 0,
};
await writeOutputs(args.outDir, context, progress);
await captureSourceRegional({
outDir: args.outDir,
baseUrl: args.baseUrl,
headers,
timeoutMs: args.timeoutMs,
entities,
generatedAt: context.generatedAt,
progress,
});
console.log(`Wrote ${entities.length + 1} markdown files and skipped-routes.json to ${args.outDir}`);
progress.complete('WordPress discovery completed', {
phase: 'discovery',
artifact: args.outDir,
count: entities.length,
unit: 'entities',
});
}
if (require.main === module) {
main().catch((error) => {
console.error(error.stack || error.message);
if (progress) {
progress.error(error && error.message ? error.message : 'WordPress discovery failed', { phase: 'discovery' });
}
process.exitCode = 1;
});
}
module.exports = {
parseArgs,
deriveEntityCandidates,
renderIndexFile,
renderPluginSection,
skippedRoutesPayload,
sourceCoveragePayload,
buildPluginCoverage,
readRoutePaths,
pluginCoveragePayload,
buildEntityStats,
reclassifyPluginCoverage,
runReclassifyCoverage,
loadDecisions,
loadTargetKnowledge,
pickChildSampleParentIds,
buildChildRoutePath,
describeChildSample,
sampleChildEntities,
sampleStructureBridgeEntities,
resolveSampleStructureRequest,
captureSourceRedirects,
readBridgeTableFully,
withRedirectCapture,
writeOutputs,
captureSourceRegional,
getAtPath,
inspectEntity,
resolveRequestBody,
normalizeResponseRecords,
findSampledIdsDependencies,
summarizeAuthMode,
summarizeBridgeAuthMode,
bridgeForbiddenCode,
BRIDGE_PLUGIN_UPDATE_REQUIRED,
createBridgeTransport,
hydrateArgsFromEnvFile,
makeSourceReadCollector,
};
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 an API key, Needs Node.js
Security
What our scanner noticed· Medium risk
- Possible data-exfiltration endpoints
- 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/resources/rp-source-wordpress · 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 rp-source-wordpress.zip