Commit 519e00b804e for woocommerce

commit 519e00b804e97ae8a1e3bd81f7f0523cb3f92206
Author: Christopher Hertel <mail@christopher-hertel.de>
Date:   Fri Nov 20 18:23:15 2026 +0100

    Add guest customers to customers-query and a customer-update ability (#70934)

    * Move the order address checks into a trait the customer abilities can share

    OrderUpdate keeps its woocommerce_ability_order_* error codes; the trait takes
    the resource name so a customer write reports woocommerce_ability_customer_*.

    * Cover guest customers in customers-query and add customer-update

    customers-query now reads the Analytics customer lookup table, so guests are
    included. A customer's id is its Analytics customer ID; registered customers
    also carry user_id and role. Order count and total spent follow Analytics
    rules (excluded statuses, net of refunds). The query selects no personal
    column. Both abilities refuse to run while Analytics is off, since the lookup
    table is only kept in sync while it is on.

    customer-update changes the name and addresses of a registered customer and
    returns the changed field names without their values. Guests are refused,
    because their addresses live on their orders.

    * Build the customer ability test fixtures with fewer writes

    Create the acting administrator once per class, build query orders with
    wc_create_order() and one Analytics import per test, and page both
    directions over one fixture. One test keeps a full order so the sync of
    real orders stays covered.

    * Keep saved address values out of customer errors and page before joining orders

    Address errors quote only values the client sent; a saved state or
    postcode that fails against a new country gets a message without it.
    Sorts that read only the lookup table pick the page first, so order
    stats are aggregated for that page instead of every customer.
    date_last_order skips refunds, and a lookup row whose user is gone is
    reported as an unknown customer instead of a permission refusal.

    * Quote each sent address value in refusals, and only the saved ones stay out

    A postcode or state the client sent is quoted again, and the sent
    country's state codes are listed again; only values the client did not
    send are left out of the message.

    * Read customers-query through the Analytics customers data store

    customers-query now calls the get_data() of the Customers report data
    store instead of its own SQL, selecting only columns without personal
    data, so counts and caching follow the report. The data store breaks
    every sort's ties by customer ID, which also stops the report from
    repeating or skipping customers across pages.

    A customer extension filter can now only return include_ids, the user
    filter the data store supports. date_last_order follows the report
    again, refunds included.

    * Skip deleted users, list extension fields, and say when customers appear

    WC_Customer swallows the "Invalid customer" exception and sets its ID to 0,
    so the catch around it never ran: a lookup row whose user was deleted came
    back as user 0 with the default role. Check the ID instead, in both
    abilities.

    customer-update built updated_fields from get_changes(), which leaves out
    the meta that extension fields write, so a call that set only an extension
    field listed nothing. It now lists each extension field sent.

    The guest refusal pointed to order-update, but no ability turns a guest's
    customer ID into order IDs, so it now only says where guest addresses live.

    customers-query's description says that a registered customer appears once
    Analytics has recorded them.

    * Leave the Analytics Customers report's sort order to its own pull request

    customers-query now pages through the report's data store as it is, so a
    sort other than id, order_count or total_spent can repeat or skip
    customers who share the sort value until the data store breaks ties.

    * Keep the total past the last page, and check saved address values only when sent

    The Analytics data store returns total 0 for a page past the last one, so
    customers-query asks for the first page again to report the real total, as
    orders-query and products-query do.

    A saved state or postcode that no longer matches the saved country blocked
    every change to that address, even a phone number. They are now checked
    only when they or the country are sent. This also applies to order-update
    and order-create, which share the checks.

    * Find customers by name, email and user ID in customers-query

    search matches the name or email that search_by picks, and user_id narrows
    to one registered customer, so an agent can turn "Jane" or an order's
    customer_id into the ID customer-update takes. The results still leave out
    names and emails.

    * Recheck edit access in customer-update, and clear the user cache when a customer save rolls back

    A guest row can be linked to an account between the permission check and
    load(), so load() checks edit access for the account it resolves.

    The customer data store reads its meta back inside the transaction, which
    leaves the rolled-back values in the user_meta cache. WC_Customer has no
    cache group, so delete_meta_cache() does not clear it.

    Also cast the permission results to bool, since the filter behind
    wc_rest_check_user_permissions() can return any value.

    * Return no customers for a search that cleans to nothing, and share the address field list

    sanitize_text_field() can empty a search that passed minLength, and the
    data store then skips the search and returns every customer.

    The ability description now names registration as a way into Analytics,
    the order abilities build their address schemas from the shared list, and
    the saved-value refusal test saves a state the sent country cannot echo.

    * Search customers by the literal term, refuse a search of 0, and scope the privacy line to core fields

    sanitize_text_field() removes percent-encoded octets, which an email address
    may contain, so an email search could match a different customer. The term
    only reaches a bound LIKE, so it is now trimmed rather than cleaned.

    The data store reads a search of "0" as no search and returns every
    customer, so the ability refuses it.

    Extension fields can return any value, so the description promises only
    that core fields leave out personal data.

    * Collapse whitespace in customer searches

    The name is matched as first and last name joined by one space, so a search
    with a double space or a tab between the names found no one.

    * Match customer emails in full, and honour the profile screen's address lock in customer-update

    A substring email search let repeated calls spell out an email the output
    leaves out. The user profile screen's woocommerce_current_user_can_edit_customer_meta_fields
    filter now also locks the ability.

    * Reuse the report cache in customers-query, and skip customer saves that change nothing

    The report's default before and after are the current time, so the cache key
    changed every second; the customers data store never reads them. customer-update
    no longer saves, or fires update hooks, when every sent value matches, reuses
    the not-found message for a user that no longer loads, and says that Analytics
    keeps old names for roles other than customer.

    * Prime extension fields for the registered customers that customers-query lists

    Trunk added a prime call to customers-query before formatting. The
    Analytics rewrite builds the WC_Customer of each registered row first,
    primes those, and leaves guests out because they have no extension
    fields. The prime test lists customers by their Analytics ID and matches
    prime calls on user_id.

    * Refuse a customer update that changes nothing

    When every sent value matches the saved one, customer-update now fails with
    woocommerce_ability_customer_unchanged, as order-update-status does for an
    unchanged status. The call stops before save, so neither the update hooks nor
    the extension syncs run for a customer that nothing wrote.

diff --git a/plugins/woocommerce/changelog/wooai-1546-guest-customer-edits b/plugins/woocommerce/changelog/wooai-1546-guest-customer-edits
new file mode 100644
index 00000000000..817e66bfbc4
--- /dev/null
+++ b/plugins/woocommerce/changelog/wooai-1546-guest-customer-edits
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Let AI agents find guest customers alongside registered ones, and update a registered customer's name and addresses.
diff --git a/plugins/woocommerce/src/Abilities/ActionableAbility.php b/plugins/woocommerce/src/Abilities/ActionableAbility.php
index 2c181da6477..044bb5943d1 100644
--- a/plugins/woocommerce/src/Abilities/ActionableAbility.php
+++ b/plugins/woocommerce/src/Abilities/ActionableAbility.php
@@ -380,6 +380,8 @@ abstract class ActionableAbility extends Ability {
 			} elseif ( $id > 0 && $object instanceof \WC_Abstract_Order ) {
 				wc_get_container()->get( \Automattic\WooCommerce\Caches\OrderCache::class )->remove( $id );
 				clean_post_cache( $id );
+			} elseif ( $id > 0 && $object instanceof \WC_Customer ) {
+				clean_user_cache( $id );
 			}
 		}
 	}
diff --git a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
index ec7f0c27b66..d3f3d3d9311 100644
--- a/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
+++ b/plugins/woocommerce/src/Abilities/ExtensibleAbilities.php
@@ -353,7 +353,8 @@ class ExtensibleAbilities {
 	 *
 	 *     @type string   $resource  Resource whose list ability applies the filters. Core's `products-query`,
 	 *                               `orders-query` and `customers-query` apply the filters of `product`, `order`
-	 *                               and `customer`. A `meta_query` for `customer` matches user meta. The list ability
+	 *                               and `customer`. A `customer` filter returns only `include_ids`, which are
+	 *                               user IDs, so it matches registered customers only. The list ability
 	 *                               of another resource must call `get_query_args()` and `add_query_filters_schema()` itself.
 	 *     @type string   $namespace Slug of the extension that owns the filter, such as `subscriptions`.
 	 *     @type string   $filter    Filter name inside the namespace, such as `subscribable`.
@@ -362,7 +363,8 @@ class ExtensibleAbilities {
 	 *                               a `meta_query`, for products also a `tax_query`, `include_ids` or
 	 *                               `exclude_ids`. Core adds each one to the query with AND. Return a
 	 *                               WP_Error to refuse the value. A `tax_query` is accepted only for
-	 *                               `product`. Any other key, or a `tax_query` for another resource, fails the call.
+	 *                               `product`. Any other key, a `tax_query` for another resource, or a key other
+	 *                               than `include_ids` for `customer`, fails the call.
 	 *                               `include_ids` and `exclude_ids` are lists of object IDs. Use them for
 	 *                               data that is not meta, such as order items or a table of the extension:
 	 *                               query that data and return the IDs that match. Core keeps the IDs that
@@ -514,6 +516,7 @@ class ExtensibleAbilities {
 					! is_array( $clauses )
 					|| ! empty( array_diff_key( $clauses, array_flip( self::QUERY_ARG_KEYS ) ) )
 					|| ( 'product' !== $resource_name && isset( $clauses['tax_query'] ) )
+					|| ( 'customer' === $resource_name && ! empty( array_diff_key( $clauses, array( 'include_ids' => true ) ) ) )
 					|| in_array( false, array_map( 'is_array', $clauses ), true )
 				) {
 					return new \WP_Error(
diff --git a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
index 18d7bfcf2cc..d231069132c 100644
--- a/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
+++ b/plugins/woocommerce/src/Internal/Abilities/AbilitiesLoader.php
@@ -18,6 +18,7 @@ use Automattic\WooCommerce\Internal\Abilities\Domain\OrderDelete;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrderUpdateStatus;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CustomersQuery;
+use Automattic\WooCommerce\Internal\Abilities\Domain\CustomerUpdate;
 use Automattic\WooCommerce\Internal\Abilities\Domain\OrdersQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CouponsQuery;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CouponCreate;
@@ -111,6 +112,7 @@ class AbilitiesLoader {
 		SettingsQuery::class,
 		SettingsUpdate::class,
 		SettingsGroupsQuery::class,
+		CustomerUpdate::class,
 	);

 	/**
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerLookup.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerLookup.php
new file mode 100644
index 00000000000..5dfecb86102
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerLookup.php
@@ -0,0 +1,79 @@
+<?php
+/**
+ * Customer lookup class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
+use Automattic\WooCommerce\Utilities\FeaturesUtil;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * The customer abilities identify customers by their Analytics customer ID, which guests have too.
+ * customers-query reads through the get_data() of the Analytics data store, so its counts match the Customers report.
+ */
+final class CustomerLookup extends CustomersDataStore {
+
+	/**
+	 * Analytics keeps the lookup table in sync only while it is on, so the customer abilities refuse to run without it.
+	 *
+	 * @return \WP_Error|null
+	 */
+	public static function get_unavailable_error(): ?\WP_Error {
+		if ( FeaturesUtil::feature_is_enabled( 'analytics' ) ) {
+			return null;
+		}
+
+		return new \WP_Error(
+			'woocommerce_ability_customer_analytics_disabled',
+			__( 'Customer data comes from WooCommerce Analytics, which is turned off on this store. Ask the store owner to turn it on under WooCommerce > Settings > Advanced > Features.', 'woocommerce' ),
+			array( 'status' => 503 )
+		);
+	}
+
+	/**
+	 * Default query vars without the report's before and after, which the customers data store never reads.
+	 * They default to the current time, so they would change the cache key every second.
+	 *
+	 * @return array
+	 */
+	public function get_default_query_vars() {
+		return array_merge(
+			parent::get_default_query_vars(),
+			array(
+				'before' => null,
+				'after'  => null,
+			)
+		);
+	}
+
+	/**
+	 * Find the WordPress user of a customer.
+	 *
+	 * @param int $customer_id Analytics customer ID.
+	 * @return int|null|false The user ID, null for a guest, or false when no customer has the ID.
+	 */
+	public static function get_user_id( int $customer_id ) {
+		global $wpdb;
+
+		$table = self::get_db_table_name();
+		$row   = $wpdb->get_row(
+			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+			$wpdb->prepare( "SELECT user_id FROM {$table} WHERE customer_id = %d", $customer_id )
+		);
+
+		if ( null === $row ) {
+			return false;
+		}
+
+		if ( null === $row->user_id ) {
+			return null;
+		}
+
+		return get_userdata( (int) $row->user_id ) ? (int) $row->user_id : false;
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerUpdate.php
new file mode 100644
index 00000000000..25c191982b4
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomerUpdate.php
@@ -0,0 +1,303 @@
+<?php
+/**
+ * Customer update ability class file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\AddressInputTrait;
+use Automattic\WooCommerce\Internal\Abilities\Domain\Traits\DomainAbilityHelpers;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Changes the name and addresses of a registered customer. The response names the changed fields
+ * without their values, so no personal data comes back.
+ */
+class CustomerUpdate extends ActionableAbility {
+
+	use AddressInputTrait;
+	use DomainAbilityHelpers;
+
+	/**
+	 * Ability name.
+	 */
+	public const ABILITY_NAME = 'woocommerce/customer-update';
+
+	/**
+	 * Fields that change() changed, as `first_name` or `billing.city`, and each extension field sent, as `extensions.<namespace>.<field>`.
+	 *
+	 * @var array<int, string>
+	 */
+	private array $updated_fields = array();
+
+	/**
+	 * Analytics customer ID from the input.
+	 *
+	 * @var int
+	 */
+	private int $customer_id = 0;
+
+	/**
+	 * Get the ability registration arguments.
+	 *
+	 * @return array
+	 *
+	 * @since 11.4.0
+	 */
+	public static function get_registration_args(): array {
+		return array(
+			'label'               => __( 'Update customer', 'woocommerce' ),
+			'description'         => __(
+				'Update the first name, last name, billing address and shipping address of a registered customer. Fields that are not sent keep their value. Guest customers have no account to update; their addresses live on their orders. The response lists the changed fields without their values. Analytics refreshes the name and address it searches only for customer roles; for other roles, woocommerce/customers-query finds the old values until their next order.',
+				'woocommerce'
+			),
+			'category'            => 'woocommerce',
+			'input_schema'        => self::build_input_schema(),
+			'output_schema'       => self::get_entity_output_schema(
+				'customer',
+				array(
+					'type'       => 'object',
+					'properties' => array(
+						'id'             => array( 'type' => 'integer' ),
+						'user_id'        => array( 'type' => 'integer' ),
+						'updated_fields' => array(
+							'type'        => 'array',
+							'description' => __( 'Fields whose value changed, such as first_name or billing.city, and each extension field sent, as extensions.<namespace>.<field>.', 'woocommerce' ),
+							'items'       => array( 'type' => 'string' ),
+						),
+					),
+				)
+			),
+			'permission_callback' => array( __CLASS__, 'can_edit_customer' ),
+			'meta'                => array(
+				'show_in_rest' => true,
+				'mcp'          => array(
+					'public' => true,
+					'type'   => 'tool',
+				),
+				// Not idempotent: the Abilities API run endpoint demands DELETE for destructive idempotent abilities.
+				'annotations'  => array(
+					'readonly'    => false,
+					'idempotent'  => false,
+					'destructive' => true,
+				),
+			),
+		);
+	}
+
+	/**
+	 * Check user edit access, with the rules of the customers REST API and the user profile screen. An ID that is a guest or
+	 * no customer passes for users who can list customers, so they get the specific error.
+	 *
+	 * @since 11.4.0
+	 * @param mixed $input Ability input.
+	 * @return bool
+	 */
+	public static function can_edit_customer( $input = array() ): bool {
+		$customer_id = self::get_id_from_input( $input );
+		if ( $customer_id <= 0 ) {
+			return false;
+		}
+
+		$user_id = CustomerLookup::get_user_id( $customer_id );
+		if ( ! is_int( $user_id ) ) {
+			return (bool) wc_rest_check_user_permissions( 'read' );
+		}
+
+		return self::can_edit_user( $user_id );
+	}
+
+	/**
+	 * The customers REST API rules, plus the filter that can lock the address fields on the user profile screen.
+	 *
+	 * @param int $user_id User ID.
+	 * @return bool
+	 */
+	private static function can_edit_user( int $user_id ): bool {
+		if ( ! wc_rest_check_user_permissions( 'edit', $user_id ) ) {
+			return false;
+		}
+
+		/**
+		 * Filters whether the current user can edit a customer's address fields, as on the user profile screen.
+		 *
+		 * @since 3.6.0
+		 * @param bool $can_edit Whether the current user can edit them.
+		 * @param int  $user_id  User ID of the customer.
+		 */
+		return (bool) apply_filters( 'woocommerce_current_user_can_edit_customer_meta_fields', current_user_can( 'manage_woocommerce' ), $user_id );
+	}
+
+	/**
+	 * Resource that the ability changes.
+	 *
+	 * @return string
+	 */
+	public function get_resource(): string {
+		return 'customer';
+	}
+
+	/**
+	 * Load the customer to change.
+	 *
+	 * @param array $input Ability input.
+	 * @return \WC_Customer|\WP_Error
+	 */
+	protected function load( array $input ) {
+		$unavailable = CustomerLookup::get_unavailable_error();
+		if ( null !== $unavailable ) {
+			return $unavailable;
+		}
+
+		$this->customer_id = $input['id'];
+		$user_id           = CustomerLookup::get_user_id( $input['id'] );
+
+		if ( false === $user_id ) {
+			return self::not_found( $input['id'] );
+		}
+
+		if ( null === $user_id ) {
+			return new \WP_Error(
+				'woocommerce_ability_customer_guest',
+				/* translators: %d: customer ID. */
+				sprintf( __( 'Customer %d is a guest, with no account to update. A guest\'s addresses are saved only on their orders, which the woocommerce/order-update ability changes by order ID.', 'woocommerce' ), $input['id'] ),
+				array( 'status' => 409 )
+			);
+		}
+
+		// The permission check may have passed for a guest whose row has since been linked to an account.
+		if ( ! self::can_edit_user( $user_id ) ) {
+			return new \WP_Error(
+				'woocommerce_ability_customer_forbidden',
+				__( 'You are not allowed to edit this customer.', 'woocommerce' ),
+				array( 'status' => rest_authorization_required_code() )
+			);
+		}
+
+		if ( empty( array_diff( array_keys( $input ), array( 'id' ) ) ) ) {
+			return new \WP_Error(
+				'woocommerce_ability_customer_no_fields',
+				__( 'No change was sent. Send at least one customer field to change, in addition to the id.', 'woocommerce' ),
+				array( 'status' => 400 )
+			);
+		}
+
+		$customer = new \WC_Customer( $user_id );
+		if ( 0 === $customer->get_id() ) {
+			return self::not_found( $input['id'] );
+		}
+		return $customer;
+	}
+
+	/**
+	 * Change the customer in memory. Every refused address field comes back in one error, and a call that changes nothing is refused.
+	 *
+	 * @param \WC_Customer $subject Customer.
+	 * @param array        $input   Ability input.
+	 * @return null|\WP_Error
+	 */
+	protected function change( $subject, array $input ) {
+		foreach ( array( 'first_name', 'last_name' ) as $field ) {
+			if ( isset( $input[ $field ] ) ) {
+				$subject->{"set_{$field}"}( sanitize_text_field( $input[ $field ] ) );
+			}
+		}
+
+		$refused = new \WP_Error();
+		foreach ( array( 'billing', 'shipping' ) as $address_type ) {
+			$error = isset( $input[ $address_type ] ) ? self::set_address( $subject, 'customer', $address_type, $input[ $address_type ] ) : null;
+			if ( is_wp_error( $error ) ) {
+				$refused->merge_from( $error );
+			}
+		}
+
+		$this->updated_fields = array();
+		foreach ( $subject->get_changes() as $key => $value ) {
+			if ( is_array( $value ) ) {
+				foreach ( array_keys( $value ) as $address_field ) {
+					$this->updated_fields[] = "{$key}.{$address_field}";
+				}
+				continue;
+			}
+			$this->updated_fields[] = $key;
+		}
+		foreach ( $input['extensions'] ?? array() as $namespace => $fields ) {
+			foreach ( array_keys( $fields ) as $field ) {
+				$this->updated_fields[] = "extensions.{$namespace}.{$field}";
+			}
+		}
+
+		if ( $refused->has_errors() ) {
+			return $refused;
+		}
+
+		if ( empty( $this->updated_fields ) ) {
+			return new \WP_Error(
+				'woocommerce_ability_customer_unchanged',
+				__( 'The customer already has every value sent, so nothing was changed.', 'woocommerce' ),
+				array( 'status' => 400 )
+			);
+		}
+
+		return null;
+	}
+
+	/**
+	 * The ability output for the saved customer.
+	 *
+	 * @param \WC_Customer $subject Saved customer.
+	 * @return array
+	 */
+	protected function prepare_response( $subject ) {
+		return array(
+			'customer' => array(
+				'id'             => $this->customer_id,
+				'user_id'        => $subject->get_id(),
+				'updated_fields' => $this->updated_fields,
+			),
+		);
+	}
+
+	/**
+	 * The error for an ID that names no customer, or one whose user no longer loads.
+	 *
+	 * @param int $customer_id Analytics customer ID.
+	 * @return \WP_Error
+	 */
+	private static function not_found( int $customer_id ): \WP_Error {
+		return new \WP_Error(
+			'woocommerce_ability_customer_not_found',
+			/* translators: %d: customer ID. */
+			sprintf( __( 'Customer %d does not exist. Use the woocommerce/customers-query ability to find the customer ID.', 'woocommerce' ), $customer_id ),
+			array( 'status' => 404 )
+		);
+	}
+
+	/**
+	 * Get the ability input schema.
+	 *
+	 * @return array
+	 */
+	private static function build_input_schema(): array {
+		return array(
+			'type'                 => 'object',
+			'properties'           => array(
+				'id'         => array(
+					'type'        => 'integer',
+					'description' => __( 'Customer ID from the woocommerce/customers-query ability.', 'woocommerce' ),
+					'minimum'     => 1,
+				),
+				'first_name' => array( 'type' => 'string' ),
+				'last_name'  => array( 'type' => 'string' ),
+				'billing'    => self::get_address_input_schema( array_merge( self::get_address_fields(), array( 'email' ) ) ),
+				'shipping'   => self::get_address_input_schema( self::get_address_fields() ),
+			),
+			'required'             => array( 'id' ),
+			'additionalProperties' => false,
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/CustomersQuery.php b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomersQuery.php
index c11595ba206..48383f7cb4c 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/CustomersQuery.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/CustomersQuery.php
@@ -17,12 +17,30 @@ if ( ! defined( 'ABSPATH' ) ) {
 }

 /**
- * Queries registered customers. The output carries no name, username, email, phone number or address.
+ * Queries registered and guest customers from the Analytics customer lookup table. The query selects
+ * no column that holds a name, username, email, phone number or address.
  */
 class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition {

 	private const DEFAULT_PER_PAGE = 10;

+	/**
+	 * Sort keys of the input, mapped to the sort keys of the Analytics customers data store.
+	 */
+	private const ORDERBY = array(
+		'last_active'     => 'date_last_active',
+		'last_order'      => 'date_last_order',
+		'registered_date' => 'date_registered',
+		'order_count'     => 'orders_count',
+		'total_spent'     => 'total_spend',
+		'id'              => 'id',
+	);
+
+	/**
+	 * Data store columns without personal data.
+	 */
+	private const FIELDS = array( 'id', 'user_id', 'date_registered', 'date_last_active', 'date_last_order', 'orders_count', 'total_spend' );
+
 	/**
 	 * Get the ability name.
 	 *
@@ -42,7 +60,7 @@ class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition
 	public static function get_registration_args(): array {
 		return array(
 			'label'               => __( 'Query customers', 'woocommerce' ),
-			'description'         => __( 'Find registered customers by ID or role, with their order count and total spent. Names, usernames, emails, phone numbers and addresses are withheld. Guest customers are not included.', 'woocommerce' ),
+			'description'         => __( 'Find registered and guest customers by ID, user ID, name or email, with their order count, total spent and activity dates, as WooCommerce Analytics counts them. A registered customer appears once Analytics has recorded them: when they register, order, or visit signed in, or the store imports historical data. Guest orders with the same email count as one guest. Core fields leave out names, usernames, emails, phone numbers and addresses.', 'woocommerce' ),
 			'category'            => 'woocommerce',
 			'input_schema'        => self::get_input_schema(),
 			'output_schema'       => self::get_output_schema(),
@@ -83,76 +101,132 @@ class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition
 	 * @return array|\WP_Error
 	 */
 	public static function execute( array $input = array() ) {
-		$exclude          = $input['exclude'] ?? array();
-		$default_per_page = empty( $input['include'] ) ? self::DEFAULT_PER_PAGE : max( 1, count( array_diff( array_unique( $input['include'] ), $exclude ) ) );
-		$page             = $input['page'] ?? 1;
-		$per_page         = $input['per_page'] ?? $default_per_page;
-		$role             = $input['role'] ?? 'customer';
-		$order            = strtoupper( $input['order'] ?? 'desc' );
-		$args             = array(
-			'number'  => $per_page,
-			'paged'   => $page,
-			// Registration dates have one-second precision, so ID keeps users registered in the same second in a stable order across pages.
-			'orderby' => 'id' === ( $input['orderby'] ?? 'registered_date' ) ? array( 'ID' => $order ) : array(
-				'registered' => $order,
-				'ID'         => $order,
-			),
-			'fields'  => 'ID',
-		);
-		if ( 'all' !== $role ) {
-			$args['role'] = $role;
+		$unavailable = CustomerLookup::get_unavailable_error();
+		if ( null !== $unavailable ) {
+			return $unavailable;
 		}

 		$extension_args = ExtensibleAbilities::get_query_args( 'customer', $input );
 		if ( is_wp_error( $extension_args ) ) {
 			return $extension_args;
 		}
-		if ( isset( $extension_args['meta_query'] ) ) {
-			$args['meta_query'] = $extension_args['meta_query']; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
+
+		$exclude  = $input['exclude'] ?? array();
+		$include  = array_values( array_diff( array_unique( $input['include'] ?? array() ), $exclude ) );
+		$page     = $input['page'] ?? 1;
+		$per_page = $input['per_page'] ?? ( empty( $input['include'] ) ? self::DEFAULT_PER_PAGE : max( 1, count( $include ) ) );
+
+		$search = isset( $input['search'] ) ? (string) preg_replace( '/\s+/', ' ', trim( $input['search'] ) ) : '';
+		if ( isset( $input['search'] ) && '' === $search ) {
+			// The data store skips an empty search, which would return every customer. The term is escaped, not cleaned, so an email keeps a literal "%41"; only whitespace is collapsed, which the name matches with single spaces.
+			return array(
+				'customers'   => array(),
+				'total'       => 0,
+				'total_pages' => 0,
+				'page'        => $page,
+				'per_page'    => $per_page,
+			);
+		}
+
+		if ( '0' === $search ) {
+			// The data store reads a search of "0" as no search, which would return every customer.
+			return new \WP_Error(
+				'woocommerce_ability_customer_search_unsupported',
+				__( 'A search for "0" alone is not supported. Search for a longer part of the name, or a full email address.', 'woocommerce' ),
+				array( 'status' => 400 )
+			);
+		}
+
+		$by_email = 'email' === ( $input['search_by'] ?? 'name' );
+		if ( $by_email && str_contains( $search, ',' ) ) {
+			// The data store splits an exact email match on commas, which would turn one search into several.
+			return new \WP_Error(
+				'woocommerce_ability_customer_search_unsupported',
+				__( 'An email search must be a single email address, without commas.', 'woocommerce' ),
+				array( 'status' => 400 )
+			);
+		}
+
+		$users = $extension_args['post__in'] ?? array();
+		if ( isset( $input['user_id'] ) ) {
+			$users = ( empty( $users ) || in_array( $input['user_id'], array_map( 'intval', $users ), true ) ) ? array( $input['user_id'] ) : array( 0 );
 		}
-		$exclude = array_merge( $exclude, $extension_args['post__not_in'] ?? array() );
-		$include = empty( $input['include'] ) ? null : $input['include'];
-		if ( isset( $extension_args['post__in'] ) ) {
-			$include = null === $include ? $extension_args['post__in'] : array_intersect( $include, $extension_args['post__in'] );
+
+		$query_args = array(
+			'fields'            => self::FIELDS,
+			'orderby'           => self::ORDERBY[ $input['orderby'] ?? 'last_active' ],
+			'order'             => $input['order'] ?? 'desc',
+			'page'              => $page,
+			'per_page'          => $per_page,
+			'user_type'         => $input['type'] ?? 'all',
+			'customers'         => empty( $input['include'] ) ? array() : ( empty( $include ) ? array( 0 ) : $include ),
+			'customers_exclude' => empty( $input['include'] ) ? $exclude : array(),
+			'users'             => $users,
+			// An email must match in full: a substring match would let repeated searches spell out an email the output leaves out.
+			'email_includes'    => $by_email ? $search : '',
+			'search'            => $by_email ? '' : $search,
+			'searchby'          => 'name',
+			'order_before'      => '',
+			'order_after'       => '',
+		);
+
+		/**
+		 * The parent docblock names these classes without their namespace.
+		 *
+		 * @var \stdClass|\WP_Error $data
+		 */
+		$data = ( new CustomerLookup() )->get_data( $query_args );
+		if ( is_wp_error( $data ) ) {
+			return $data;
 		}
-		if ( null !== $include ) {
-			$include         = array_values( array_diff( $include, $exclude ) );
-			$args['include'] = empty( $include ) ? array( 0 ) : $include;
-		} elseif ( ! empty( $exclude ) ) {
-			$args['exclude'] = array_values( array_unique( $exclude ) );
+
+		$total = (int) $data->total;
+		if ( 0 === $total && empty( $data->data ) && $page > 1 ) {
+			/**
+			 * The data store skips its count when the requested page is past the last one.
+			 *
+			 * @var \stdClass|\WP_Error $first_page
+			 */
+			$first_page = ( new CustomerLookup() )->get_data( array_merge( $query_args, array( 'page' => 1 ) ) );
+			if ( is_wp_error( $first_page ) ) {
+				return $first_page;
+			}
+			$total = (int) $first_page->total;
 		}

-		$query    = new \WP_User_Query( $args );
-		$user_ids = array_map( 'intval', $query->get_results() );
-		cache_users( $user_ids );
+		$rows = $data->data;
+		cache_users( array_filter( array_column( $rows, 'user_id' ) ) );

-		$customers = array();
-		foreach ( $user_ids as $user_id ) {
-			try {
-				$customer = new \WC_Customer( $user_id );
-			} catch ( \Exception $e ) {
+		$accounts = array();
+		foreach ( $rows as $index => $row ) {
+			if ( empty( $row['user_id'] ) ) {
+				continue;
+			}
+			$account = new \WC_Customer( (int) $row['user_id'] );
+			if ( 0 === $account->get_id() ) {
 				wc_get_logger()->warning(
 					'The customers-query ability skipped a user that does not load as a customer, so total counts more customers than it returns.',
 					array(
-						'source'        => 'woocommerce-abilities',
-						'user_id'       => $user_id,
-						'error_message' => $e->getMessage(),
+						'source'  => 'woocommerce-abilities',
+						'user_id' => (int) $row['user_id'],
 					)
 				);
+				unset( $rows[ $index ] );
 				continue;
 			}
-			$customers[] = $customer;
+			$accounts[ $index ] = $account;
 		}
-		ExtensibleAbilities::prime( 'customer', $customers );
-		foreach ( $customers as $index => $customer ) {
-			$formatted = self::format_customer( $customer );
+		ExtensibleAbilities::prime( 'customer', $accounts );
+
+		$customers = array();
+		foreach ( $rows as $index => $row ) {
+			$formatted = self::format_customer( $row, $accounts[ $index ] ?? null );
 			if ( is_wp_error( $formatted ) ) {
 				return $formatted;
 			}
-			$customers[ $index ] = $formatted;
+			$customers[] = $formatted;
 		}

-		$total = (int) $query->get_total();
 		return array(
 			'customers'   => $customers,
 			'total'       => $total,
@@ -163,26 +237,47 @@ class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition
 	}

 	/**
-	 * Format a customer. Every field here must stay free of personal data.
+	 * Format a customer row. Every field here must stay free of personal data. Only registered
+	 * customers have a role and extension fields, because extensions read them from WC_Customer.
 	 *
-	 * @param \WC_Customer $customer Customer.
+	 * @param array             $row      Row of the Analytics customers data store; a guest has user ID 0.
+	 * @param \WC_Customer|null $customer Account of a registered customer, or null for a guest.
+	 * @phpstan-param array{id: int, user_id: int, date_registered: ?string, date_last_active: ?string, date_last_order: ?string, orders_count: int, total_spend: float} $row
 	 * @return array|\WP_Error
 	 */
-	private static function format_customer( \WC_Customer $customer ) {
+	private static function format_customer( array $row, ?\WC_Customer $customer ) {
 		$output = array(
-			'id'                 => $customer->get_id(),
-			'role'               => $customer->get_role(),
-			'is_paying_customer' => (bool) $customer->get_is_paying_customer(),
-			'order_count'        => (int) $customer->get_order_count(),
-			'total_spent'        => self::format_amount_for_response( $customer->get_total_spent() ),
-			'date_created'       => self::format_date_for_response( $customer->get_date_created() ),
-			'date_modified'      => self::format_date_for_response( $customer->get_date_modified() ),
-		);
-		return ExtensibleAbilities::add_fields_to_object(
-			array_filter( $output, static fn( $value ) => null !== $value ),
-			'customer',
-			$customer
+			'id'               => (int) $row['id'],
+			'order_count'      => (int) $row['orders_count'],
+			'total_spent'      => wc_format_decimal( $row['total_spend'], wc_get_price_decimals() ),
+			'date_registered'  => self::format_lookup_date( $row['date_registered'], false ),
+			'date_last_active' => self::format_lookup_date( $row['date_last_active'], true ),
+			'date_last_order'  => self::format_lookup_date( $row['date_last_order'], false ),
 		);
+		$output = array_filter( $output, static fn( $value ) => null !== $value );
+
+		if ( null === $customer ) {
+			return $output;
+		}
+
+		$output['user_id'] = $customer->get_id();
+		$output['role']    = $customer->get_role();
+		return ExtensibleAbilities::add_fields_to_object( $output, 'customer', $customer );
+	}
+
+	/**
+	 * Format a date of the lookup or order stats table as UTC.
+	 *
+	 * @param string|null $date   MySQL date.
+	 * @param bool        $is_gmt Whether the column holds UTC rather than store time.
+	 * @return string|null
+	 */
+	private static function format_lookup_date( ?string $date, bool $is_gmt ): ?string {
+		if ( null === $date || '' === $date || 0 === strpos( $date, '0000-00-00' ) ) {
+			return null;
+		}
+
+		return self::format_date_for_response( $is_gmt ? new \WC_DateTime( $date, new \DateTimeZone( 'UTC' ) ) : new \WC_DateTime( $date, wp_timezone() ) );
 	}

 	/**
@@ -201,16 +296,26 @@ class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition
 				array(
 					'type'       => 'object',
 					'properties' => array(
-						'id'                 => array( 'type' => 'integer' ),
-						'role'               => array( 'type' => 'string' ),
-						'is_paying_customer' => array( 'type' => 'boolean' ),
-						'order_count'        => array( 'type' => 'integer' ),
-						'total_spent'        => array(
+						'id'               => array(
+							'type'        => 'integer',
+							'description' => __( 'Analytics customer ID. Guests have one too.', 'woocommerce' ),
+						),
+						'user_id'          => array(
+							'type'        => 'integer',
+							'description' => __( 'WordPress user ID. Only registered customers have one.', 'woocommerce' ),
+						),
+						'role'             => array( 'type' => 'string' ),
+						'order_count'      => array(
+							'type'        => 'integer',
+							'description' => __( 'Orders in the statuses that Analytics counts.', 'woocommerce' ),
+						),
+						'total_spent'      => array(
 							'type'        => 'string',
-							'description' => __( 'Decimal amount in the store currency, from paid orders.', 'woocommerce' ),
+							'description' => __( 'Decimal amount of those orders after refunds, in the store currency.', 'woocommerce' ),
 						),
-						'date_created'       => $date,
-						'date_modified'      => $date,
+						'date_registered'  => $date,
+						'date_last_active' => $date,
+						'date_last_order'  => $date,
 					),
 				),
 				'customer'
@@ -240,33 +345,48 @@ class CustomersQuery extends AbstractDomainAbility implements AbilityDefinition
 		$schema = array(
 			'type'                 => 'object',
 			'properties'           => array(
-				'include'  => $ids + array(
+				'include'   => $ids + array(
 					'description' => __( 'Return only these customer IDs, up to 100. Without per_page, they come back in one page.', 'woocommerce' ),
 					'maxItems'    => 100,
 				),
-				'exclude'  => $ids + array( 'description' => __( 'Leave out these customer IDs.', 'woocommerce' ) ),
-				'role'     => array(
+				'exclude'   => $ids + array( 'description' => __( 'Leave out these customer IDs.', 'woocommerce' ) ),
+				'user_id'   => array(
+					'type'        => 'integer',
+					'description' => __( 'Return only the registered customer with this WordPress user ID, such as the customer_id of an order.', 'woocommerce' ),
+					'minimum'     => 1,
+				),
+				'search'    => array(
 					'type'        => 'string',
-					'description' => __( 'User role to list. Use all for every registered user. Defaults to customer.', 'woocommerce' ),
-					'enum'        => array_merge( array( 'all' ), array_keys( wp_roles()->get_names() ) ),
-					'default'     => 'customer',
+					'description' => __( 'With search_by name, return only customers whose name contains this text. With search_by email, return only the customer with this exact email address.', 'woocommerce' ),
+					'minLength'   => 1,
+					'maxLength'   => 200,
+				),
+				'search_by' => array(
+					'type'    => 'string',
+					'enum'    => array( 'name', 'email' ),
+					'default' => 'name',
+				),
+				'type'      => array(
+					'type'    => 'string',
+					'enum'    => array( 'all', 'registered', 'guest' ),
+					'default' => 'all',
 				),
-				'orderby'  => array(
+				'orderby'   => array(
 					'type'    => 'string',
-					'enum'    => array( 'registered_date', 'id' ),
-					'default' => 'registered_date',
+					'enum'    => array_keys( self::ORDERBY ),
+					'default' => 'last_active',
 				),
-				'order'    => array(
+				'order'     => array(
 					'type'    => 'string',
 					'enum'    => array( 'asc', 'desc' ),
 					'default' => 'desc',
 				),
-				'page'     => array(
+				'page'      => array(
 					'type'    => 'integer',
 					'default' => 1,
 					'minimum' => 1,
 				),
-				'per_page' => array(
+				'per_page'  => array(
 					'type'        => 'integer',
 					'description' => __( 'Customers per page. Defaults to 10, or to the number of IDs in include.', 'woocommerce' ),
 					'minimum'     => 1,
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
index 69ffb83d8cb..53dc8ed23ed 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderCreate.php
@@ -145,7 +145,7 @@ class OrderCreate extends ActionableAbility {
 		}

 		foreach ( array( 'billing', 'shipping' ) as $address_type ) {
-			$error = isset( $input[ $address_type ] ) ? self::set_address( $subject, $address_type, $input[ $address_type ] ) : null;
+			$error = isset( $input[ $address_type ] ) ? self::set_address( $subject, 'order', $address_type, $input[ $address_type ] ) : null;
 			if ( is_wp_error( $error ) ) {
 				$refused->merge_from( $error );
 			}
@@ -260,8 +260,8 @@ class OrderCreate extends ActionableAbility {
 					'description' => __( 'Order status slug without the wc- prefix. Defaults to the default status of the store.', 'woocommerce' ),
 					'enum'        => self::get_allowed_order_status_slugs(),
 				),
-				'billing'        => self::get_address_input_schema( array_merge( self::shipping_address_fields(), array( 'email' ) ) ),
-				'shipping'       => self::get_address_input_schema( self::shipping_address_fields() ),
+				'billing'        => self::get_address_input_schema( array_merge( self::get_address_fields(), array( 'email' ) ) ),
+				'shipping'       => self::get_address_input_schema( self::get_address_fields() ),
 				'customer_note'  => array( 'type' => 'string' ),
 				'line_items'     => array(
 					'type'        => 'array',
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
index a9e5b9efd8e..db2fa6409f9 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/OrderUpdate.php
@@ -121,7 +121,7 @@ class OrderUpdate extends ActionableAbility {

 		$refused = new \WP_Error();
 		foreach ( array( 'billing', 'shipping' ) as $address_type ) {
-			$error = isset( $input[ $address_type ] ) ? self::set_address( $subject, $address_type, $input[ $address_type ] ) : null;
+			$error = isset( $input[ $address_type ] ) ? self::set_address( $subject, 'order', $address_type, $input[ $address_type ] ) : null;
 			if ( is_wp_error( $error ) ) {
 				$refused->merge_from( $error );
 			}
@@ -354,8 +354,8 @@ class OrderUpdate extends ActionableAbility {
 					'type'    => 'integer',
 					'minimum' => 1,
 				),
-				'billing'        => self::get_address_input_schema( array_merge( self::shipping_address_fields(), array( 'email' ) ) ),
-				'shipping'       => self::get_address_input_schema( self::shipping_address_fields() ),
+				'billing'        => self::get_address_input_schema( array_merge( self::get_address_fields(), array( 'email' ) ) ),
+				'shipping'       => self::get_address_input_schema( self::get_address_fields() ),
 				'customer_note'  => array( 'type' => 'string' ),
 				'line_items'     => array(
 					'type'        => 'array',
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/AddressInputTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/AddressInputTrait.php
new file mode 100644
index 00000000000..348f3e13deb
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/AddressInputTrait.php
@@ -0,0 +1,189 @@
+<?php
+/**
+ * Address input trait file.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Abilities\Domain\Traits;
+
+defined( 'ABSPATH' ) || exit;
+
+/**
+ * Billing and shipping address input for abilities that write an order or a customer.
+ */
+trait AddressInputTrait {
+
+	/**
+	 * Address fields that the shipping address has. The billing address also has `email`.
+	 *
+	 * @return array<int, string>
+	 */
+	private static function get_address_fields(): array {
+		return array( 'first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'phone' );
+	}
+
+	/**
+	 * Check the sent fields of an address against the object, then set the fields
+	 * that pass. A bad country keeps the saved country, state and postcode, because
+	 * the state and postcode checks depend on the country. A saved state or postcode
+	 * is checked only when it or the country is sent, so an outdated saved value
+	 * doesn't block changes to the other fields.
+	 *
+	 * @param \WC_Order|\WC_Customer $subject       Order or customer.
+	 * @param string                 $resource_name Resource in the error codes: order or customer.
+	 * @param string                 $type          Address type: billing or shipping.
+	 * @param array                  $address       Address fields to change.
+	 * @return null|\WP_Error
+	 */
+	private static function set_address( $subject, string $resource_name, string $type, array $address ): ?\WP_Error {
+		$address = wc_clean( $address );
+		$refused = new \WP_Error();
+		if ( ! empty( $address['email'] ) && ! is_email( $address['email'] ) ) {
+			$refused->merge_from(
+				self::address_error(
+					$resource_name,
+					$type,
+					'email',
+					__( 'The billing email is not a valid email address. Send a valid address.', 'woocommerce' )
+				)
+			);
+			unset( $address['email'] );
+		}
+
+		$country  = $address['country'] ?? $subject->{"get_{$type}_country"}();
+		$state    = $address['state'] ?? $subject->{"get_{$type}_state"}();
+		$postcode = $address['postcode'] ?? $subject->{"get_{$type}_postcode"}();
+
+		$sent_fields = array_keys( (array) $address );
+		$sent        = static fn( string ...$fields ): bool => empty( array_diff( $fields, $sent_fields ) );
+
+		$check_state    = $sent( 'state' ) || $sent( 'country' );
+		$check_postcode = $sent( 'postcode' ) || $sent( 'country' );
+
+		if ( ( $check_state || $check_postcode ) && '' !== $country && ! array_key_exists( $country, WC()->countries->get_countries() ) ) {
+			$refused->merge_from(
+				self::address_error(
+					$resource_name,
+					$type,
+					'country',
+					$sent( 'country' )
+						/* translators: %s: country sent by the client. */
+						? sprintf( __( '"%s" is not a valid country. Send an ISO 3166-1 alpha-2 country code, such as PT.', 'woocommerce' ), $country )
+						: __( 'The saved country is not valid. Send an ISO 3166-1 alpha-2 country code, such as PT.', 'woocommerce' )
+				)
+			);
+			unset( $address['country'], $address['state'], $address['postcode'] );
+		} else {
+			$states = WC()->countries->get_states( $country );
+
+			if ( $check_state && '' !== $state && ! empty( $states ) && ! array_key_exists( $state, $states ) ) {
+				$refused->merge_from(
+					self::address_error(
+						$resource_name,
+						$type,
+						'state',
+						self::get_state_message( $sent( 'state' ), $sent( 'country' ), $state, $country, array_keys( $states ) )
+					)
+				);
+				unset( $address['state'] );
+			}
+
+			if ( $check_postcode && '' !== $postcode && '' !== $country ) {
+				if ( ! \WC_Validation::is_postcode( $postcode, $country ) ) {
+					$refused->merge_from(
+						self::address_error(
+							$resource_name,
+							$type,
+							'postcode',
+							self::get_postcode_message( $sent( 'postcode' ), $sent( 'country' ), $postcode, $country )
+						)
+					);
+					unset( $address['postcode'] );
+				} elseif ( isset( $address['postcode'] ) ) {
+					$address['postcode'] = wc_format_postcode( $postcode, $country );
+				}
+			}
+		}
+
+		foreach ( $address as $key => $value ) {
+			$subject->{"set_{$type}_{$key}"}( $value );
+		}
+
+		return $refused->has_errors() ? $refused : null;
+	}
+
+	/**
+	 * Explain a state that does not belong to the country, quoting only values the client sent.
+	 *
+	 * @param bool               $state_sent   Whether the client sent the state.
+	 * @param bool               $country_sent Whether the client sent the country.
+	 * @param string             $state        State code.
+	 * @param string             $country      Country code.
+	 * @param array<int, string> $state_codes  State codes of the country.
+	 * @return string
+	 */
+	private static function get_state_message( bool $state_sent, bool $country_sent, string $state, string $country, array $state_codes ): string {
+		if ( $state_sent && $country_sent ) {
+			/* translators: 1: state sent by the client, 2: country code sent by the client, 3: comma-separated state codes. */
+			return sprintf( __( '"%1$s" is not a state of %2$s. Send the state with one of these codes: %3$s.', 'woocommerce' ), $state, $country, implode( ', ', $state_codes ) );
+		}
+		if ( $country_sent ) {
+			/* translators: 1: country code sent by the client, 2: comma-separated state codes. */
+			return sprintf( __( 'The saved state is not a state of %1$s. Send the state with one of these codes: %2$s.', 'woocommerce' ), $country, implode( ', ', $state_codes ) );
+		}
+		/* translators: %s: state sent by the client. */
+		return sprintf( __( '"%s" is not a state of the saved country. Send the country and the state together.', 'woocommerce' ), $state );
+	}
+
+	/**
+	 * Explain a postcode that does not match the country, quoting only values the client sent.
+	 *
+	 * @param bool   $postcode_sent Whether the client sent the postcode.
+	 * @param bool   $country_sent  Whether the client sent the country.
+	 * @param string $postcode      Postcode.
+	 * @param string $country       Country code.
+	 * @return string
+	 */
+	private static function get_postcode_message( bool $postcode_sent, bool $country_sent, string $postcode, string $country ): string {
+		if ( $postcode_sent && $country_sent ) {
+			/* translators: 1: postcode sent by the client, 2: country code sent by the client. */
+			return sprintf( __( '"%1$s" is not a valid postcode for %2$s. Send a postcode in the format of that country.', 'woocommerce' ), $postcode, $country );
+		}
+		if ( $country_sent ) {
+			/* translators: %s: country code sent by the client. */
+			return sprintf( __( 'The saved postcode is not valid for %s. Send a postcode in the format of that country.', 'woocommerce' ), $country );
+		}
+		/* translators: %s: postcode sent by the client. */
+		return sprintf( __( '"%s" is not a valid postcode for the saved country. Send a postcode in the format of that country.', 'woocommerce' ), $postcode );
+	}
+
+	/**
+	 * Build the error for an address field.
+	 *
+	 * @param string $resource_name Resource in the error code: order or customer.
+	 * @param string $type          Address type: billing or shipping.
+	 * @param string $field         Address field.
+	 * @param string $message       What is wrong and what to send.
+	 * @return \WP_Error
+	 */
+	private static function address_error( string $resource_name, string $type, string $field, string $message ): \WP_Error {
+		return new \WP_Error( "woocommerce_ability_{$resource_name}_{$type}_{$field}_invalid", $message, array( 'status' => 400 ) );
+	}
+
+	/**
+	 * Get the input schema of an address.
+	 *
+	 * @param array<int, string> $fields Address fields.
+	 * @return array
+	 */
+	private static function get_address_input_schema( array $fields ): array {
+		return array(
+			'type'                 => 'object',
+			'description'          => __( 'Countries use ISO 3166-1 alpha-2 codes, and states use WooCommerce state codes.', 'woocommerce' ),
+			'properties'           => array_fill_keys( $fields, array( 'type' => 'string' ) ),
+			'additionalProperties' => false,
+			'minProperties'        => 1,
+		);
+	}
+}
diff --git a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
index 93f5d73f004..f1291cd1bb9 100644
--- a/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
+++ b/plugins/woocommerce/src/Internal/Abilities/Domain/Traits/OrderEditTrait.php
@@ -19,6 +19,8 @@ defined( 'ABSPATH' ) || exit;
  */
 trait OrderEditTrait {

+	use AddressInputTrait;
+
 	/**
 	 * Product lines that change() added or gave a new quantity, for a stock change after the save.
 	 *
@@ -137,95 +139,6 @@ trait OrderEditTrait {
 		return null;
 	}

-	/**
-	 * Check the sent fields of an address against the order, then set the fields
-	 * that pass. A bad country keeps the saved country, state and postcode, because
-	 * the state and postcode checks depend on the country.
-	 *
-	 * @param \WC_Order $order   Order.
-	 * @param string    $type    Address type: billing or shipping.
-	 * @param array     $address Address fields to change.
-	 * @return null|\WP_Error
-	 */
-	private static function set_address( \WC_Order $order, string $type, array $address ): ?\WP_Error {
-		$address = wc_clean( $address );
-		$refused = new \WP_Error();
-		if ( ! empty( $address['email'] ) && ! is_email( $address['email'] ) ) {
-			$refused->merge_from(
-				self::address_error(
-					$type,
-					'email',
-					__( 'The billing email is not a valid email address. Send a valid address.', 'woocommerce' )
-				)
-			);
-			unset( $address['email'] );
-		}
-
-		$country  = $address['country'] ?? $order->{"get_{$type}_country"}();
-		$state    = $address['state'] ?? $order->{"get_{$type}_state"}();
-		$postcode = $address['postcode'] ?? $order->{"get_{$type}_postcode"}();
-
-		if ( '' !== $country && ! array_key_exists( $country, WC()->countries->get_countries() ) ) {
-			$refused->merge_from(
-				self::address_error(
-					$type,
-					'country',
-					/* translators: %s: country sent by the client. */
-					sprintf( __( '"%s" is not a valid country. Send an ISO 3166-1 alpha-2 country code, such as PT.', 'woocommerce' ), $country )
-				)
-			);
-			unset( $address['country'], $address['state'], $address['postcode'] );
-		} else {
-			$states = WC()->countries->get_states( $country );
-
-			if ( '' !== $state && ! empty( $states ) && ! array_key_exists( $state, $states ) ) {
-				$refused->merge_from(
-					self::address_error(
-						$type,
-						'state',
-						/* translators: 1: state sent by the client or kept from the order, 2: country code, 3: comma-separated state codes. */
-						sprintf( __( '"%1$s" is not a state of %2$s. Send the state with one of these codes: %3$s.', 'woocommerce' ), $state, $country, implode( ', ', array_keys( $states ) ) )
-					)
-				);
-				unset( $address['state'] );
-			}
-
-			if ( '' !== $postcode && '' !== $country ) {
-				if ( ! \WC_Validation::is_postcode( $postcode, $country ) ) {
-					$refused->merge_from(
-						self::address_error(
-							$type,
-							'postcode',
-							/* translators: 1: postcode sent by the client or kept from the order, 2: country code. */
-							sprintf( __( '"%1$s" is not a valid postcode for %2$s. Send a postcode in the format of that country.', 'woocommerce' ), $postcode, $country )
-						)
-					);
-					unset( $address['postcode'] );
-				} elseif ( isset( $address['postcode'] ) ) {
-					$address['postcode'] = wc_format_postcode( $postcode, $country );
-				}
-			}
-		}
-
-		foreach ( $address as $key => $value ) {
-			$order->{"set_{$type}_{$key}"}( $value );
-		}
-
-		return $refused->has_errors() ? $refused : null;
-	}
-
-	/**
-	 * Build the error for an address field.
-	 *
-	 * @param string $type    Address type: billing or shipping.
-	 * @param string $field   Address field.
-	 * @param string $message What is wrong and what to send.
-	 * @return \WP_Error
-	 */
-	private static function address_error( string $type, string $field, string $message ): \WP_Error {
-		return new \WP_Error( "woocommerce_ability_order_{$type}_{$field}_invalid", $message, array( 'status' => 400 ) );
-	}
-
 	/**
 	 * Change a shipping line in memory, or add a new one when the line has no ID.
 	 *
@@ -352,20 +265,4 @@ trait OrderEditTrait {
 	private static function quantity_error( \Exception $exception ): \WP_Error {
 		return new \WP_Error( 'woocommerce_ability_order_line_item_quantity_invalid', $exception->getMessage(), array( 'status' => 400 ) );
 	}
-
-	/**
-	 * Get the input schema of an address.
-	 *
-	 * @param array<int, string> $fields Address fields.
-	 * @return array
-	 */
-	private static function get_address_input_schema( array $fields ): array {
-		return array(
-			'type'                 => 'object',
-			'description'          => __( 'Countries use ISO 3166-1 alpha-2 codes, and states use WooCommerce state codes.', 'woocommerce' ),
-			'properties'           => array_fill_keys( $fields, array( 'type' => 'string' ) ),
-			'additionalProperties' => false,
-			'minProperties'        => 1,
-		);
-	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
index c188799dd85..412272d76f5 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/AbilitiesLoaderTest.php
@@ -60,6 +60,7 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 		'woocommerce/order-notes-query',
 		'woocommerce/payment-gateways-query',
 		'woocommerce/customers-query',
+		'woocommerce/customer-update',
 		'woocommerce/product-review-update',
 		'woocommerce/product-review-reply',
 		'woocommerce/product-reviews-query',
@@ -374,6 +375,11 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 				'idempotent'  => true,
 				'destructive' => false,
 			),
+			'woocommerce/customer-update'             => array(
+				'readonly'    => false,
+				'idempotent'  => false,
+				'destructive' => true,
+			),
 			'woocommerce/product-review-update'       => array(
 				'readonly'    => false,
 				'idempotent'  => false,
@@ -1263,6 +1269,13 @@ class AbilitiesLoaderTest extends \WC_Unit_Test_Case {
 					'enabled' => true,
 				),
 			),
+			'customer-update'             => array(
+				'woocommerce/customer-update',
+				array(
+					'id'         => 1,
+					'first_name' => 'Denied',
+				),
+			),
 		);
 	}

diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomerUpdateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomerUpdateTest.php
new file mode 100644
index 00000000000..5b8236784bd
--- /dev/null
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomerUpdateTest.php
@@ -0,0 +1,434 @@
+<?php
+/**
+ * Customer update tests.
+ */
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;
+
+use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
+use Automattic\WooCommerce\Enums\OrderStatus;
+use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
+use Automattic\WooCommerce\Internal\Abilities\Domain\CustomerUpdate;
+
+/**
+ * Tests the customer-update ability.
+ */
+class CustomerUpdateTest extends \WC_Unit_Test_Case {
+
+	/**
+	 * An administrator, who may edit users.
+	 *
+	 * @var int
+	 */
+	private static $user_id;
+
+	/**
+	 * Create the fixtures that no test changes beyond its own transaction.
+	 *
+	 * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
+	 */
+	public static function wpSetUpBeforeClass( $factory ): void {
+		self::$user_id = $factory->user->create( array( 'role' => 'administrator' ) );
+	}
+
+	/**
+	 * Log in as the administrator.
+	 */
+	public function setUp(): void {
+		parent::setUp();
+		wp_set_current_user( self::$user_id );
+	}
+
+	/**
+	 * Run the ability as it is registered.
+	 *
+	 * @param array $input Ability input.
+	 * @return mixed
+	 */
+	private function execute( array $input ) {
+		return wp_get_ability( CustomerUpdate::ABILITY_NAME )->execute( $input );
+	}
+
+	/**
+	 * Create a registered customer in the Analytics lookup table.
+	 *
+	 * @return array{0: int, 1: int} Analytics customer ID and user ID.
+	 */
+	private function registered_customer(): array {
+		$user_id  = self::factory()->user->create( array( 'role' => 'customer' ) );
+		$customer = new \WC_Customer( $user_id );
+		$customer->set_billing_country( 'US' );
+		$customer->set_billing_state( 'CA' );
+		$customer->set_billing_postcode( '94110' );
+		$customer->set_billing_city( 'Old city' );
+		$customer->save();
+		CustomersDataStore::update_registered_customer( $user_id );
+		return array( (int) CustomersDataStore::get_customer_id_by_user_id( $user_id ), $user_id );
+	}
+
+	/**
+	 * @testdox Should change the names and addresses, and list the changed fields without their values.
+	 */
+	public function test_updates_names_and_addresses(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+
+		$result = $this->execute(
+			array(
+				'id'         => $id,
+				'first_name' => 'Ana',
+				'billing'    => array(
+					'city'     => 'San Francisco',
+					'postcode' => '94110',
+				),
+				'shipping'   => array(
+					'country'  => 'GB',
+					'postcode' => 'sw1a1aa',
+				),
+			)
+		);
+
+		$this->assertIsArray( $result );
+		$this->assertSame( $id, $result['customer']['id'] );
+		$this->assertSame( $user_id, $result['customer']['user_id'] );
+		$this->assertEqualsCanonicalizing( array( 'first_name', 'billing.city', 'shipping.country', 'shipping.postcode' ), $result['customer']['updated_fields'], 'A field sent with its saved value did not change.' );
+		$this->assertStringNotContainsString( 'San Francisco', (string) wp_json_encode( $result ) );
+
+		$customer = new \WC_Customer( $user_id );
+		$this->assertSame( 'Ana', $customer->get_first_name() );
+		$this->assertSame( 'San Francisco', $customer->get_billing_city() );
+		$this->assertSame( 'CA', $customer->get_billing_state(), 'A field that is not sent keeps its value.' );
+		$this->assertSame( 'SW1A 1AA', $customer->get_shipping_postcode(), 'The postcode is formatted for its country.' );
+	}
+
+	/**
+	 * @testdox Should refuse every invalid address field in one error and save nothing.
+	 */
+	public function test_refuses_invalid_address_fields(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+
+		$result = $this->execute(
+			array(
+				'id'         => $id,
+				'first_name' => 'Ana',
+				'billing'    => array(
+					'state' => 'XX',
+					'email' => 'not-an-email',
+				),
+				'shipping'   => array( 'country' => 'ZZ' ),
+			)
+		);
+
+		$this->assertWPError( $result );
+		$this->assertEqualsCanonicalizing(
+			array( 'woocommerce_ability_customer_billing_state_invalid', 'woocommerce_ability_customer_billing_email_invalid', 'woocommerce_ability_customer_shipping_country_invalid' ),
+			$result->get_error_codes()
+		);
+		$this->assertSame( '', ( new \WC_Customer( $user_id ) )->get_first_name() );
+	}
+
+	/**
+	 * @testdox Should change other address fields while the saved state and postcode no longer match the saved country.
+	 */
+	public function test_outdated_saved_address_does_not_block_other_fields(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+		$customer             = new \WC_Customer( $user_id );
+		$customer->set_billing_state( 'XX' );
+		$customer->set_billing_postcode( 'not-a-zip' );
+		$customer->save();
+
+		$result = $this->execute(
+			array(
+				'id'      => $id,
+				'billing' => array( 'phone' => '555-0199' ),
+			)
+		);
+
+		$this->assertSame( array( 'billing.phone' ), $result['customer']['updated_fields'] );
+		$this->assertSame( '555-0199', ( new \WC_Customer( $user_id ) )->get_billing_phone() );
+	}
+
+	/**
+	 * @testdox Should not quote the saved state and postcode when they fail against a sent country.
+	 */
+	public function test_refusal_does_not_quote_saved_values(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+		$customer             = new \WC_Customer( $user_id );
+		$customer->set_billing_state( 'NY' );
+		$customer->save();
+
+		$result = $this->execute(
+			array(
+				'id'      => $id,
+				'billing' => array( 'country' => 'CA' ),
+			)
+		);
+
+		$this->assertWPError( $result );
+		$this->assertEqualsCanonicalizing( array( 'woocommerce_ability_customer_billing_state_invalid', 'woocommerce_ability_customer_billing_postcode_invalid' ), $result->get_error_codes() );
+		$messages = implode( ' ', $result->get_error_messages() );
+		$this->assertStringNotContainsString( 'NY', $messages );
+		$this->assertStringNotContainsString( '94110', $messages );
+		$this->assertStringNotContainsString( '"', $messages, 'Only sent values are quoted.' );
+	}
+
+	/**
+	 * @testdox Should report a lookup row whose user is gone as an unknown customer.
+	 */
+	public function test_stale_lookup_row_is_not_found(): void {
+		global $wpdb;
+		$wpdb->insert(
+			CustomersDataStore::get_db_table_name(),
+			array(
+				'user_id'         => self::$user_id + 100000,
+				'date_registered' => '2026-01-01 00:00:00',
+			)
+		);
+		$id = (int) $wpdb->insert_id;
+
+		$this->assertTrue( CustomerUpdate::can_edit_customer( array( 'id' => $id ) ) );
+		$result = $this->execute(
+			array(
+				'id'         => $id,
+				'first_name' => 'Ana',
+			)
+		);
+		$this->assertSame( 'woocommerce_ability_customer_not_found', $result->get_error_code() );
+	}
+
+	/**
+	 * @testdox Should refuse a guest, an unknown customer and a call with nothing to change.
+	 */
+	public function test_refuses_guests_unknown_ids_and_empty_changes(): void {
+		$order = wc_create_order( array( 'status' => OrderStatus::COMPLETED ) );
+		$order->set_billing_email( 'guest@example.test' );
+		$order->save();
+		\WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+		$guest = (int) CustomersDataStore::get_guest_id_by_email( 'guest@example.test' );
+
+		$result = $this->execute(
+			array(
+				'id'         => $guest,
+				'first_name' => 'Ana',
+			)
+		);
+		$this->assertSame( 'woocommerce_ability_customer_guest', $result->get_error_code() );
+
+		$result = $this->execute(
+			array(
+				'id'         => $guest + 1000,
+				'first_name' => 'Ana',
+			)
+		);
+		$this->assertSame( 'woocommerce_ability_customer_not_found', $result->get_error_code() );
+
+		$result = $this->execute( array( 'id' => $this->registered_customer()[0] ) );
+		$this->assertSame( 'woocommerce_ability_customer_no_fields', $result->get_error_code() );
+	}
+
+	/**
+	 * @testdox Should let a shop manager edit a customer but not an administrator.
+	 */
+	public function test_permissions(): void {
+		list( $id )    = $this->registered_customer();
+		$admin_user_id = get_current_user_id();
+		add_filter( 'woocommerce_analytics_customer_roles', static fn() => array( 'customer', 'administrator' ) );
+		CustomersDataStore::update_registered_customer( $admin_user_id );
+		$admin = (int) CustomersDataStore::get_customer_id_by_user_id( $admin_user_id );
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'shop_manager' ) ) );
+		$this->assertTrue( CustomerUpdate::can_edit_customer( array( 'id' => $id ) ) );
+		$this->assertFalse( CustomerUpdate::can_edit_customer( array( 'id' => $admin ) ) );
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'customer' ) ) );
+		$this->assertFalse( CustomerUpdate::can_edit_customer( array( 'id' => $id ) ) );
+	}
+
+	/**
+	 * @testdox Should refuse an edit that the user profile screen's address filter locks.
+	 */
+	public function test_honours_the_profile_address_lock(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+		add_filter( 'woocommerce_current_user_can_edit_customer_meta_fields', '__return_false' );
+
+		$this->assertFalse( CustomerUpdate::can_edit_customer( array( 'id' => $id ) ) );
+		$result = $this->execute(
+			array(
+				'id'         => $id,
+				'first_name' => 'Changed',
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertNotSame( 'Changed', ( new \WC_Customer( $user_id ) )->get_first_name() );
+	}
+
+	/**
+	 * @testdox Should recheck edit access when a guest is linked to an account after the permission check.
+	 */
+	public function test_rechecks_access_for_guest_linked_after_permission_check(): void {
+		global $wpdb;
+		$order = wc_create_order( array( 'status' => OrderStatus::COMPLETED ) );
+		$order->set_billing_email( 'linked@example.test' );
+		$order->save();
+		\WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+		$guest = (int) CustomersDataStore::get_guest_id_by_email( 'linked@example.test' );
+
+		wp_set_current_user( self::factory()->user->create( array( 'role' => 'shop_manager' ) ) );
+		add_action(
+			'wp_before_execute_ability',
+			static function () use ( $wpdb, $guest ) {
+				$wpdb->update( CustomersDataStore::get_db_table_name(), array( 'user_id' => self::$user_id ), array( 'customer_id' => $guest ) );
+			}
+		);
+
+		$result = $this->execute(
+			array(
+				'id'         => $guest,
+				'first_name' => 'Ana',
+			)
+		);
+
+		$this->assertSame( 'woocommerce_ability_customer_forbidden', $result->get_error_code() );
+		$this->assertSame( '', ( new \WC_Customer( self::$user_id ) )->get_first_name() );
+	}
+
+	/**
+	 * @testdox Should refuse to run while Analytics is off.
+	 */
+	public function test_refuses_without_analytics(): void {
+		list( $id ) = $this->registered_customer();
+		update_option( 'woocommerce_analytics_enabled', 'no' );
+
+		$result = $this->execute(
+			array(
+				'id'         => $id,
+				'first_name' => 'Ana',
+			)
+		);
+
+		$this->assertSame( 'woocommerce_ability_customer_analytics_disabled', $result->get_error_code() );
+	}
+
+	/**
+	 * Run a test with the core resources and the given extension callbacks registered, and restore
+	 * the registry after it.
+	 *
+	 * @param callable $register Registers fields or syncs inside woocommerce_extensible_abilities_init.
+	 * @param callable $test     Receives a CustomerUpdate built while they are registered.
+	 */
+	private function with_extensions( callable $register, callable $test ): void {
+		$saved = array();
+		foreach ( array( 'resources', 'fields', 'validators', 'filters', 'syncs' ) as $name ) {
+			$property = new \ReflectionProperty( ExtensibleAbilities::class, $name );
+			$property->setAccessible( true );
+			$saved[ $name ] = $property->getValue();
+			$property->setValue( null, array() );
+		}
+		try {
+			update_option( 'woocommerce_feature_extensible_abilities_enabled', 'yes' );
+			add_action( 'woocommerce_extensible_abilities_resources_init', array( AbilitiesLoader::class, 'register_core_resources' ), 0 );
+			do_action( 'woocommerce_extensible_abilities_resources_init' );
+			add_action( 'woocommerce_extensible_abilities_init', $register );
+			do_action( 'woocommerce_extensible_abilities_init' );
+			$test( new CustomerUpdate( CustomerUpdate::ABILITY_NAME, CustomerUpdate::get_registration_args() ) );
+		} finally {
+			foreach ( $saved as $name => $value ) {
+				$property = new \ReflectionProperty( ExtensibleAbilities::class, $name );
+				$property->setAccessible( true );
+				$property->setValue( null, $value );
+			}
+		}
+	}
+
+	/**
+	 * @testdox Should list an extension field it set, since extension fields write meta that get_changes() leaves out.
+	 */
+	public function test_lists_extension_fields_it_set(): void {
+		$this->with_extensions(
+			static function () {
+				ExtensibleAbilities::register_field(
+					array(
+						'resource'      => 'customer',
+						'namespace'     => 'test-ext',
+						'field'         => 'tier',
+						'output_schema' => array( 'type' => 'string' ),
+						'input_schema'  => array( 'type' => 'string' ),
+						'get_callback'  => static fn( \WC_Customer $customer ) => (string) $customer->get_meta( '_test_tier' ),
+						'set_callback'  => static function ( \WC_Customer $customer, $value ) {
+							$customer->update_meta_data( '_test_tier', $value );
+							return null;
+						},
+					)
+				);
+			},
+			function ( CustomerUpdate $ability ) {
+				list( $id, $user_id ) = $this->registered_customer();
+				$result               = $ability->execute(
+					array(
+						'id'         => $id,
+						'extensions' => array( 'test-ext' => array( 'tier' => 'gold' ) ),
+					)
+				);
+				$this->assertSame( array( 'extensions.test-ext.tier' ), $result['customer']['updated_fields'] );
+				$this->assertSame( 'gold', ( new \WC_Customer( $user_id ) )->get_meta( '_test_tier' ) );
+			}
+		);
+	}
+
+	/**
+	 * @testdox Should refuse, without saving, a call whose every sent value matches the saved one.
+	 */
+	public function test_refuses_unchanged_customer(): void {
+		list( $id ) = $this->registered_customer();
+		$saves      = did_action( 'woocommerce_update_customer' );
+
+		$result = $this->execute(
+			array(
+				'id'      => $id,
+				'billing' => array( 'city' => 'Old city' ),
+			)
+		);
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_customer_unchanged', $result->get_error_code() );
+		$this->assertSame( 400, $result->get_error_data()['status'] );
+		$this->assertSame( $saves, did_action( 'woocommerce_update_customer' ), 'An unchanged customer is not saved.' );
+
+		$this->execute(
+			array(
+				'id'      => $id,
+				'billing' => array( 'city' => 'New city' ),
+			)
+		);
+		$this->assertSame( $saves + 1, did_action( 'woocommerce_update_customer' ) );
+	}
+
+	/**
+	 * @testdox Should not leave the cached user meta of a save that a sync refused.
+	 */
+	public function test_refused_sync_leaves_no_cached_address(): void {
+		$this->with_extensions(
+			static function () {
+				ExtensibleAbilities::register_sync(
+					array(
+						'resource'  => 'customer',
+						'namespace' => 'test-ext',
+						'callback'  => static fn() => new \WP_Error( 'test_refused', 'Refused.' ),
+					)
+				);
+			},
+			function ( CustomerUpdate $ability ) {
+				list( $id, $user_id ) = $this->registered_customer();
+				$result               = $ability->execute(
+					array(
+						'id'      => $id,
+						'billing' => array( 'city' => 'New city' ),
+					)
+				);
+				$this->assertWPError( $result );
+				$this->assertSame( 'Old city', ( new \WC_Customer( $user_id ) )->get_billing_city() );
+			}
+		);
+	}
+}
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomersQueryTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomersQueryTest.php
index 6d35638e3d1..6e84ad7911b 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomersQueryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/CustomersQueryTest.php
@@ -8,6 +8,7 @@ declare( strict_types=1 );
 namespace Automattic\WooCommerce\Tests\Internal\Abilities\Domain;

 use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
+use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
 use Automattic\WooCommerce\Enums\OrderStatus;
 use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
 use Automattic\WooCommerce\Internal\Abilities\Domain\CustomersQuery;
@@ -29,7 +30,7 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 	 *
 	 * @var int
 	 */
-	private static $administrator_id;
+	private static $user_id;

 	/**
 	 * Create the fixtures that no test changes beyond its own transaction.
@@ -37,7 +38,7 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 	 * @param \WP_UnitTest_Factory $factory WordPress unit test factory.
 	 */
 	public static function wpSetUpBeforeClass( $factory ): void {
-		self::$administrator_id = $factory->user->create( array( 'role' => 'administrator' ) );
+		self::$user_id = $factory->user->create( array( 'role' => 'administrator' ) );
 	}

 	/**
@@ -45,135 +46,327 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 	 */
 	public function setUp(): void {
 		parent::setUp();
-		wp_set_current_user( self::$administrator_id );
+		wp_set_current_user( self::$user_id );
 		$this->sut = new \WP_Ability( CustomersQuery::get_name(), CustomersQuery::get_registration_args() );
 	}

 	/**
-	 * Create a customer with personal data on every field that holds it.
+	 * Create a registered customer with personal data on every field that holds it.
 	 *
-	 * @param string $role User role.
-	 * @return int
+	 * @return array{0: int, 1: int} Analytics customer ID and user ID.
 	 */
-	private function customer( string $role = 'customer' ): int {
-		$id       = self::factory()->user->create(
+	private function registered_customer(): array {
+		$user_id  = self::factory()->user->create(
 			array(
-				'role'       => $role,
+				'role'       => 'customer',
 				'user_login' => 'private-login-' . wp_generate_password( 6, false ),
 				'user_email' => 'private-' . wp_generate_password( 6, false ) . '@example.test',
 			)
 		);
-		$customer = new \WC_Customer( $id );
+		$customer = new \WC_Customer( $user_id );
 		$customer->set_first_name( 'Privatefirst' );
 		$customer->set_last_name( 'Privatelast' );
 		$customer->set_billing_address_1( 'Private Street 1' );
+		$customer->set_billing_city( 'Privatecity' );
 		$customer->set_billing_phone( '555-0100' );
 		$customer->set_billing_email( 'private-billing@example.test' );
 		$customer->set_shipping_address_1( 'Private Street 2' );
 		$customer->save();
-		return $id;
+		CustomersDataStore::update_registered_customer( $user_id );
+		return array( (int) CustomersDataStore::get_customer_id_by_user_id( $user_id ), $user_id );
 	}

 	/**
-	 * @testdox Should return order count and total spent with no personal data anywhere in the output.
+	 * Create an order without line items; the query reads only its Analytics rows. Call
+	 * sync_analytics() before querying.
+	 *
+	 * @param int    $user_id User ID, or 0 for a guest.
+	 * @param string $status  Order status.
+	 * @param string $email   Billing email of a guest order.
+	 * @return \WC_Order
 	 */
-	public function test_returns_spend_without_personal_data(): void {
-		$id    = $this->customer();
-		$order = \WC_Helper_Order::create_order( $id );
-		$order->set_status( OrderStatus::COMPLETED );
+	private function order( int $user_id, string $status = OrderStatus::COMPLETED, string $email = '' ): \WC_Order {
+		$order = wc_create_order(
+			array(
+				'customer_id' => $user_id,
+				'status'      => $status,
+			)
+		);
+		if ( '' !== $email ) {
+			$order->set_billing_email( $email );
+			$order->set_billing_first_name( 'Privateguest' );
+			$order->set_billing_phone( '555-0199' );
+		}
+		$order->set_total( '10.00' );
 		$order->save();
-		\WC_Helper_Order::create_order( $id );
+		return $order;
+	}

-		$result = $this->sut->execute( array( 'include' => array( $id ) ) );
+	/**
+	 * Run the Analytics import of every order created so far.
+	 */
+	private function sync_analytics(): void {
+		\WC_Helper_Queue::run_all_pending( 'wc-admin-data' );
+	}
+
+	/**
+	 * Create guests with one completed order each, in one Analytics import.
+	 *
+	 * @param int $count Number of guests.
+	 * @return array<int, int> Analytics customer IDs.
+	 */
+	private function guest_customers( int $count ): array {
+		$emails = array();
+		for ( $i = 0; $i < $count; $i++ ) {
+			$emails[] = 'private-guest-' . wp_generate_password( 6, false ) . '@example.test';
+			$this->order( 0, OrderStatus::COMPLETED, end( $emails ) );
+		}
+		$this->sync_analytics();
+		return array_map( static fn( string $email ) => (int) CustomersDataStore::get_guest_id_by_email( $email ), $emails );
+	}
+
+	/**
+	 * @testdox Should count the orders Analytics counts, with no personal data anywhere in the output.
+	 */
+	public function test_returns_spend_without_personal_data(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+		$completed            = \WC_Helper_Order::create_order( $user_id );
+		$completed->set_status( OrderStatus::COMPLETED );
+		$completed->save();
+		$this->order( $user_id, OrderStatus::FAILED );
+		list( $guest ) = $this->guest_customers( 1 );
+
+		$result = $this->sut->execute( array( 'include' => array( $id, $guest ) ) );

 		$this->assertIsArray( $result );
-		$this->assertSame( 1, $result['total'] );
-		$item = $result['customers'][0];
-		$this->assertSame( $id, $item['id'] );
-		$this->assertSame( 'customer', $item['role'] );
-		$this->assertSame( 2, $item['order_count'], 'Every order counts, paid or not.' );
-		$this->assertSame( wc_format_decimal( $order->get_total(), 2 ), $item['total_spent'], 'Only the paid order adds to the spend.' );
-		$allowed = array( 'id', 'role', 'is_paying_customer', 'order_count', 'total_spent', 'date_created', 'date_modified' );
-		$this->assertSame( array(), array_diff( array_keys( $item ), $allowed ), 'A new customer field must be checked for personal data before it joins the allowlist.' );
+		$this->assertSame( 2, $result['total'] );
+		$items = array_column( $result['customers'], null, 'id' );
+		$this->assertSame( $user_id, $items[ $id ]['user_id'] );
+		$this->assertSame( 'customer', $items[ $id ]['role'] );
+		$this->assertSame( 1, $items[ $id ]['order_count'], 'A failed order is excluded from Analytics by default.' );
+		$this->assertSame( wc_format_decimal( $completed->get_total(), 2 ), $items[ $id ]['total_spent'] );
+		$this->assertArrayHasKey( 'date_last_order', $items[ $id ] );
+		$this->assertSame( 1, $items[ $guest ]['order_count'] );
+		$this->assertArrayNotHasKey( 'user_id', $items[ $guest ], 'A guest has no user.' );
+		$this->assertArrayNotHasKey( 'role', $items[ $guest ] );
+
+		$allowed = array( 'id', 'user_id', 'role', 'order_count', 'total_spent', 'date_registered', 'date_last_active', 'date_last_order' );
+		foreach ( $items as $item ) {
+			$this->assertSame( array(), array_diff( array_keys( $item ), $allowed ), 'A new customer field must be checked for personal data before it joins the allowlist.' );
+		}
 		$json = (string) wp_json_encode( $result );
-		foreach ( array( 'private', 'Private', '555-0100', '@' ) as $needle ) {
+		foreach ( array( 'private', 'Private', '555-01', '@' ) as $needle ) {
 			$this->assertStringNotContainsString( $needle, $json );
 		}
 	}

 	/**
-	 * @testdox Should list only customers by default, every user with role all, and count all matches across pages.
+	 * @testdox Should list registered customers, guests or both by type.
 	 */
-	public function test_role_and_paging(): void {
-		$customers = array( $this->customer(), $this->customer(), $this->customer() );
-		$this->customer( 'shop_manager' );
+	public function test_type_filter(): void {
+		list( $registered ) = $this->registered_customer();
+		list( $guest )      = $this->guest_customers( 1 );
+		$input              = array( 'include' => array( $registered, $guest ) );
+
+		$this->assertEqualsCanonicalizing( array( $registered, $guest ), array_column( $this->sut->execute( $input )['customers'], 'id' ) );
+		$this->assertSame( array( $registered ), array_column( $this->sut->execute( $input + array( 'type' => 'registered' ) )['customers'], 'id' ) );
+		$this->assertSame( array( $guest ), array_column( $this->sut->execute( $input + array( 'type' => 'guest' ) )['customers'], 'id' ) );
+	}
+
+	/**
+	 * @testdox Should page by customer ID in both directions and count all matches across pages.
+	 */
+	public function test_paging(): void {
+		$ascending = array_merge( array( $this->registered_customer()[0], $this->registered_customer()[0] ), $this->guest_customers( 1 ) );
+		sort( $ascending );
+
+		$directions = array(
+			'asc'  => $ascending,
+			'desc' => array_reverse( $ascending ),
+		);
+		foreach ( $directions as $order => $ids ) {
+			$pages = array();
+			for ( $page = 1; $page <= 2; $page++ ) {
+				$result = $this->sut->execute(
+					array(
+						'include'  => $ids,
+						'orderby'  => 'id',
+						'order'    => $order,
+						'per_page' => 2,
+						'page'     => $page,
+					)
+				);
+				$this->assertSame( 3, $result['total'], "Total, {$order}." );
+				$this->assertSame( 2, $result['total_pages'], "Total pages, {$order}." );
+				$pages = array_merge( $pages, array_column( $result['customers'], 'id' ) );
+			}
+			$this->assertSame( $ids, $pages, "Pages, {$order}." );
+		}
+	}
+
+	/**
+	 * @testdox Should report the matching total on a page past the last one, and zero when nothing matches.
+	 */
+	public function test_page_past_last_keeps_total(): void {
+		$ids = $this->guest_customers( 3 );

 		$result = $this->sut->execute(
 			array(
-				'per_page' => 2,
+				'include'  => $ids,
 				'orderby'  => 'id',
-				'order'    => 'asc',
+				'per_page' => 2,
+				'page'     => 5,
 			)
 		);
+		$this->assertSame( array(), $result['customers'] );
 		$this->assertSame( 3, $result['total'] );
 		$this->assertSame( 2, $result['total_pages'] );
-		$this->assertSame( array_slice( $customers, 0, 2 ), array_column( $result['customers'], 'id' ) );

 		$result = $this->sut->execute(
 			array(
-				'per_page' => 2,
-				'page'     => 2,
-				'orderby'  => 'id',
-				'order'    => 'asc',
+				'include' => array( max( $ids ) + 1000 ),
+				'page'    => 2,
 			)
 		);
-		$this->assertSame( array( $customers[2] ), array_column( $result['customers'], 'id' ) );
+		$this->assertSame( 0, $result['total'] );
+		$this->assertSame( 0, $result['total_pages'] );
+	}

-		$this->assertSame( 1, $this->sut->execute( array( 'role' => 'shop_manager' ) )['total'] );
-		$this->assertSame( count_users()['total_users'], $this->sut->execute( array( 'role' => 'all' ) )['total'] );
+	/**
+	 * @testdox Should reuse the report cache for an identical query.
+	 */
+	public function test_reuses_report_cache(): void {
+		$this->registered_customer();
+		$writes = 0;
+		$count  = static function ( $expiration, $key ) use ( &$writes ) {
+			if ( str_starts_with( $key, 'wc_report_customers' ) ) {
+				++$writes;
+			}
+			return $expiration;
+		};
+		add_filter( 'woocommerce_reports_cache_expiration', $count, 10, 2 );
+
+		$this->sut->execute( array() );
+		// The report's default dates carry the UTC offset, so a key built from them would change with it, as it does with the clock.
+		update_option( 'gmt_offset', 5 );
+		$this->sut->execute( array() );
+
+		$this->assertSame( 1, $writes, 'The second query reads the cached result.' );
 	}

 	/**
-	 * @testdox Should order customers registered in the same second by ID, so pages neither repeat nor skip them.
-	 * @testWith ["desc"]
-	 *           ["asc"]
-	 * @param string $order Sort direction.
+	 * @testdox Should find customers by name, email and user ID without returning the name or email.
 	 */
-	public function test_same_second_registrations_page_by_id( string $order ): void {
-		$ids = array();
-		for ( $i = 0; $i < 3; $i++ ) {
-			$ids[] = self::factory()->user->create(
+	public function test_search_and_user_id(): void {
+		list( $id, $user_id ) = $this->registered_customer();
+		list( $other )        = $this->registered_customer();
+		$guest                = $this->guest_customers( 1 )[0];
+		$email                = get_userdata( $user_id )->user_email;
+		$ids                  = static fn( array $result ): array => array_column( $result['customers'], 'id' );
+
+		$this->assertSame( array( $guest ), $ids( $this->sut->execute( array( 'search' => 'Privateguest' ) ) ), 'A guest is found by the name on their orders.' );
+		$this->assertEqualsCanonicalizing( array( $id, $other ), $ids( $this->sut->execute( array( 'search' => 'privatefirst privatelast' ) ) ) );
+		$this->assertEqualsCanonicalizing( array( $id, $other ), $ids( $this->sut->execute( array( 'search' => "privatefirst \t privatelast" ) ) ), 'Runs of whitespace match the single space between the names.' );
+
+		$result = $this->sut->execute(
+			array(
+				'search'    => $email,
+				'search_by' => 'email',
+			)
+		);
+		$this->assertSame( array( $id ), $ids( $result ) );
+		$this->assertStringNotContainsString( $email, (string) wp_json_encode( $result ) );
+		$this->assertSame( array(), $ids( $this->sut->execute( array( 'search' => $email ) ) ), 'search_by defaults to the name.' );
+		$this->assertSame(
+			array(),
+			$ids(
+				$this->sut->execute(
+					array(
+						'search'    => substr( $email, 0, -1 ),
+						'search_by' => 'email',
+					)
+				)
+			),
+			'An email search matches the whole address, so it cannot spell one out.'
+		);
+		$this->assertSame(
+			'woocommerce_ability_customer_search_unsupported',
+			$this->sut->execute(
 				array(
-					'role'            => 'customer',
-					'user_registered' => '2026-01-01 00:00:00',
+					'search'    => $email . ',other@example.test',
+					'search_by' => 'email',
 				)
-			);
-		}
-		if ( 'desc' === $order ) {
-			$ids = array_reverse( $ids );
-		}
+			)->get_error_code(),
+			'An email search with a comma is refused rather than split into several addresses.'
+		);

-		$pages = array();
-		for ( $page = 1; $page <= 3; $page++ ) {
-			$result = $this->sut->execute(
-				array(
-					'order'    => $order,
-					'per_page' => 1,
-					'page'     => $page,
+		$result = $this->sut->execute( array( 'search' => '   ' ) );
+		$this->assertSame( array(), $result['customers'], 'A whitespace-only search matches no one, not everyone.' );
+		$this->assertSame( 0, $result['total'] );
+
+		$this->assertSame( 'woocommerce_ability_customer_search_unsupported', $this->sut->execute( array( 'search' => '0' ) )->get_error_code(), 'A search of "0" is refused rather than read as no search.' );
+
+		$encoded_user = self::factory()->user->create(
+			array(
+				'role'       => 'customer',
+				'user_email' => 'orders%41@example.test',
+			)
+		);
+		$plain_user   = self::factory()->user->create(
+			array(
+				'role'       => 'customer',
+				'user_email' => 'orders@example.test',
+			)
+		);
+		CustomersDataStore::update_registered_customer( $encoded_user );
+		CustomersDataStore::update_registered_customer( $plain_user );
+		$result = $this->sut->execute(
+			array(
+				'search'    => 'orders%41@example.test',
+				'search_by' => 'email',
+			)
+		);
+		$this->assertSame( array( (int) CustomersDataStore::get_customer_id_by_user_id( $encoded_user ) ), $ids( $result ), 'An email search keeps its literal characters.' );
+
+		$this->assertSame( array( $id ), $ids( $this->sut->execute( array( 'user_id' => $user_id ) ) ) );
+		$this->assertSame(
+			array(),
+			$ids(
+				$this->sut->execute(
+					array(
+						'user_id' => $user_id,
+						'type'    => 'guest',
+					)
 				)
-			);
-			$pages  = array_merge( $pages, array_column( $result['customers'], 'id' ) );
-		}
-		$this->assertSame( $ids, $pages );
+			)
+		);
+	}
+
+	/**
+	 * @testdox Should sort by total spent.
+	 */
+	public function test_orderby_total_spent(): void {
+		list( $big, $big_user ) = $this->registered_customer();
+		$this->order( $big_user );
+		$this->order( $big_user );
+		list( $small ) = $this->guest_customers( 1 );
+
+		$result = $this->sut->execute(
+			array(
+				'include' => array( $small, $big ),
+				'orderby' => 'total_spent',
+			)
+		);
+		$this->assertSame( array( $big, $small ), array_column( $result['customers'], 'id' ) );
 	}

 	/**
 	 * @testdox Should return the IDs in include in one page, minus the IDs in exclude.
 	 */
 	public function test_include_and_exclude(): void {
-		$ids = array();
-		for ( $i = 0; $i < 12; $i++ ) {
-			$ids[] = $this->customer();
+		$ids = $this->guest_customers( 6 );
+		for ( $i = 0; $i < 6; $i++ ) {
+			$ids[] = $this->registered_customer()[0];
 		}

 		$result = $this->sut->execute( array( 'include' => $ids ) );
@@ -188,12 +381,38 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 		);
 		$this->assertEqualsCanonicalizing( array( $ids[0], $ids[2] ), array_column( $result['customers'], 'id' ) );

-		$result = $this->sut->execute( array( 'exclude' => array_slice( $ids, 1 ) ) );
-		$this->assertSame( array( $ids[0] ), array_column( $result['customers'], 'id' ) );
+		$result = $this->sut->execute(
+			array(
+				'include' => array( $ids[0] ),
+				'exclude' => array( $ids[0] ),
+			)
+		);
+		$this->assertSame( array(), $result['customers'] );
+		$this->assertSame( 0, $result['total'] );
+	}
+
+	/**
+	 * @testdox Should skip a lookup row whose user was deleted, while total still counts it.
+	 */
+	public function test_skips_stale_lookup_row(): void {
+		global $wpdb;
+		list( $id ) = $this->registered_customer();
+		$wpdb->insert(
+			CustomersDataStore::get_db_table_name(),
+			array(
+				'user_id'         => self::$user_id + 100000,
+				'date_registered' => '2026-01-01 00:00:00',
+			)
+		);
+		$stale = (int) $wpdb->insert_id;
+
+		$result = $this->sut->execute( array( 'include' => array( $id, $stale ) ) );
+		$this->assertSame( array( $id ), array_column( $result['customers'], 'id' ) );
+		$this->assertSame( 2, $result['total'] );
 	}

 	/**
-	 * @testdox Should add extension fields and filters only while the extensible abilities feature is on.
+	 * @testdox Should add extension fields and filters to registered customers only, and only while the extensible abilities feature is on.
 	 */
 	public function test_extension_fields_and_filters(): void {
 		$saved = array();
@@ -205,17 +424,19 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 		}
 		try {
 			update_option( 'woocommerce_feature_extensible_abilities_enabled', 'no' );
-			$ids      = array( $this->customer(), $this->customer(), $this->customer() );
-			$input    = array( 'include' => $ids );
-			$baseline = CustomersQuery::execute( $input );
-			$schema   = CustomersQuery::get_registration_args()['output_schema'];
+			$registered = array( $this->registered_customer(), $this->registered_customer() );
+			$guest      = $this->guest_customers( 1 )[0];
+			$input      = array( 'include' => array( $registered[0][0], $registered[1][0], $guest ) );
+			$baseline   = CustomersQuery::execute( $input );
+			$schema     = CustomersQuery::get_registration_args()['output_schema'];

 			update_option( 'woocommerce_feature_extensible_abilities_enabled', 'yes' );
 			add_action( 'woocommerce_extensible_abilities_resources_init', array( AbilitiesLoader::class, 'register_core_resources' ), 0 );
 			do_action( 'woocommerce_extensible_abilities_resources_init' );
+			$member = $registered[1][1];
 			add_action(
 				'woocommerce_extensible_abilities_init',
-				static function () use ( $ids ) {
+				static function () use ( $member ) {
 					ExtensibleAbilities::register_field(
 						array(
 							'resource'      => 'customer',
@@ -231,7 +452,7 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 							'namespace' => 'test-ext',
 							'filter'    => 'members',
 							'schema'    => array( 'type' => 'boolean' ),
-							'callback'  => static fn( bool $members ) => array( 'include_ids' => $members ? array_slice( $ids, 1 ) : array( $ids[0] ) ),
+							'callback'  => static fn( bool $members ) => $members ? array( 'include_ids' => array( $member ) ) : array( 'exclude_ids' => array( $member ) ),
 						)
 					);
 				}
@@ -240,19 +461,17 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 			$ability = new \WP_Ability( CustomersQuery::get_name(), CustomersQuery::get_registration_args() );

 			$result = $ability->execute( $input );
-			$this->assertCount( 3, $result['customers'] );
-			foreach ( $result['customers'] as $customer ) {
-				$this->assertSame( 'tier-' . $customer['id'], $customer['extensions']['test-ext']['tier'] );
+			$items  = array_column( $result['customers'], null, 'id' );
+			$this->assertCount( 3, $items );
+			foreach ( $registered as list( $id, $user_id ) ) {
+				$this->assertSame( 'tier-' . $user_id, $items[ $id ]['extensions']['test-ext']['tier'] );
 			}
+			$this->assertArrayNotHasKey( 'extensions', $items[ $guest ], 'A guest has no WC_Customer for extensions to read.' );
 			$this->assertSame( 'string', $ability->get_output_schema()['properties']['customers']['items']['properties']['extensions']['properties']['test-ext']['properties']['tier']['type'] );

-			$result = $ability->execute(
-				array(
-					'include' => array( $ids[0], $ids[1] ),
-					'filters' => array( 'extensions' => array( 'test-ext' => array( 'members' => true ) ) ),
-				)
-			);
-			$this->assertSame( array( $ids[1] ), array_column( $result['customers'], 'id' ), 'An extension filter narrows include instead of adding to it.' );
+			$members = static fn( bool $value ) => $input + array( 'filters' => array( 'extensions' => array( 'test-ext' => array( 'members' => $value ) ) ) );
+			$this->assertSame( array( $registered[1][0] ), array_column( $ability->execute( $members( true ) )['customers'], 'id' ), 'An extension filter narrows include instead of adding to it.' );
+			$this->assertSame( 'woocommerce_ability_extension_filter_failed', $ability->execute( $members( false ) )->get_error_code(), 'A customer filter can only include user IDs.' );

 			update_option( 'woocommerce_feature_extensible_abilities_enabled', 'no' );
 			$this->assertSame( $baseline, CustomersQuery::execute( $input ) );
@@ -266,6 +485,18 @@ class CustomersQueryTest extends \WC_Unit_Test_Case {
 		}
 	}

+	/**
+	 * @testdox Should refuse to run while Analytics is off, because the lookup table is not kept in sync.
+	 */
+	public function test_refuses_without_analytics(): void {
+		update_option( 'woocommerce_analytics_enabled', 'no' );
+
+		$result = $this->sut->execute();
+
+		$this->assertWPError( $result );
+		$this->assertSame( 'woocommerce_ability_customer_analytics_disabled', $result->get_error_code() );
+	}
+
 	/**
 	 * @testdox Should let shop managers read customers and refuse users who cannot list users.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
index b1f98cb9c2f..c071b49df47 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Abilities/Domain/OrderUpdateTest.php
@@ -65,6 +65,26 @@ class OrderUpdateTest extends WC_Unit_Test_Case {
 		$this->assertSame( 'SW1A 1AA', $order->get_shipping_postcode() );
 	}

+	/**
+	 * @testdox Should change other address fields while the saved state no longer matches the saved country.
+	 */
+	public function test_outdated_saved_state_does_not_block_other_fields(): void {
+		$order = WC_Helper_Order::create_order();
+		$order->set_billing_country( 'US' );
+		$order->set_billing_state( 'XX' );
+		$order->save();
+
+		$result = $this->execute(
+			array(
+				'id'      => $order->get_id(),
+				'billing' => array( 'phone' => '555-0199' ),
+			)
+		);
+
+		$this->assertNotWPError( $result );
+		$this->assertSame( '555-0199', wc_get_order( $order->get_id() )->get_billing_phone() );
+	}
+
 	/**
 	 * @testdox Should refuse every bad address field in one error, check the state against the saved country, and save nothing.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
index 0edea741b86..3ca566928c9 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AbilitiesApi/ExtensibleAbilitiesTest.php
@@ -9,6 +9,7 @@ namespace Automattic\WooCommerce\Tests\Internal\AbilitiesApi;

 use Automattic\WooCommerce\Abilities\ExtensibleAbilities;
 use Automattic\WooCommerce\Abilities\ActionableAbility;
+use Automattic\WooCommerce\Admin\API\Reports\Customers\DataStore as CustomersDataStore;
 use Automattic\WooCommerce\Enums\ProductStatus;
 use Automattic\WooCommerce\Internal\Abilities\AbilitiesLoader;
 use Automattic\WooCommerce\Internal\DataStores\Orders\DataSynchronizer;
@@ -1060,11 +1061,13 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {

 		$list = $this->run_ability( $ability, $create_input() )[ $list_key ];

-		$ids = array_column( $list, 'id' );
+		// A customer's id is its Analytics customer ID; extensions get the WC_Customer of its user.
+		$id_key = 'customer' === $resource_name ? 'user_id' : 'id';
+		$ids    = array_column( $list, $id_key );
 		$this->assertCount( 2, $ids );
 		$this->assertSame( array( array( 'test-ext', $ids ), array( 'other_ext', $ids ) ), $calls );
 		foreach ( $list as $listed ) {
-			$this->assertSame( 'primed-' . $listed['id'], $listed['extensions']['test-ext']['primed'] );
+			$this->assertSame( 'primed-' . $listed[ $id_key ], $listed['extensions']['test-ext']['primed'] );
 		}
 	}

@@ -1090,7 +1093,12 @@ class ExtensibleAbilitiesTest extends \WC_REST_Unit_Test_Case {
 				'woocommerce/customers-query',
 				'customers',
 				static function (): array {
-					return array( 'include' => self::factory()->user->create_many( 2, array( 'role' => 'customer' ) ) );
+					$customer_ids = array();
+					foreach ( self::factory()->user->create_many( 2, array( 'role' => 'customer' ) ) as $user_id ) {
+						CustomersDataStore::update_registered_customer( $user_id );
+						$customer_ids[] = (int) CustomersDataStore::get_customer_id_by_user_id( $user_id );
+					}
+					return array( 'include' => $customer_ids );
 				},
 			),
 			'product_term'   => array(