Commit 0384417ec4e for woocommerce

commit 0384417ec4eed3e35593a509ec422d26877140b5
Author: AnnaMag <AnnaMag@users.noreply.github.com>
Date:   Tue Nov 17 09:49:15 2026 +0100

    Agent readiness: require permalinks that can serve UCP discovery (#70816)

    * Agent readiness: require permalinks that can serve UCP discovery

    UcpDiscovery only serves /.well-known/ucp with pretty permalinks without
    index.php, so on other stores UCP could report Active at an address that
    404s. UcpDiscovery::can_serve() is now the one place that says whether
    the store can serve it, and a required readiness check reads it. When
    UCP discovery works on any permalinks, can_serve() changes and the check
    passes on its own.

    * Agent readiness: keep UCP discovery's permalink rule as it was

    Only the Plain permalinks case is in scope; index.php permalinks are left
    to #70680, which serves discovery on any permalinks.

    * Agent readiness: check that /.well-known/ucp serves WooCommerce's profile

    UcpDiscovery::can_serve() now passes with pretty permalinks unless a file
    WooCommerce didn't write is in the way, and with Plain permalinks only
    when the static file is one WooCommerce wrote, marked by a links entry
    with rel "woocommerce". It reads the same marker and file path as the
    static file work in #70680 and #70727, so the check is right in either
    merge order, and UCP discovery's own rewrite registration is unchanged.

    * Agent readiness: read the UCP file only when readable, and at most 64 KB

    * Agent readiness: say why /.well-known/ucp can't be served, read from the file each time

    UcpDiscovery::serve_status() replaces can_serve(). It reads the permalink
    setting and the static file on every call and returns ok, no_file,
    file_in_the_way or file_outdated, so nothing is stored. The UCP address
    condition passes only on ok and shows the fix for the reason.

    A file WooCommerce wrote is outdated when its ucp part differs from the
    current profile (for example after a move to HTTPS); unreadable, non-JSON
    or cut-short files count as in the way.

    * Agent readiness: test the outdated-file fix and an unreadable UCP file

    * Agent readiness: tell merchants to delete an outdated UCP file, which works with UCP off

    The file is only rewritten while UCP is on, and the failing check stops UCP
    being turned on, so reloading couldn't fix it. Deleting the file and leaving
    Plain permalinks does, and the test checks that. Tests also remove the temp
    folders they create.

    * Agent readiness: say how to make the UCP address reachable

    The status row only linked to permalinks. Say when to delete the
    discovery file or fix its permissions, and don't treat index.php
    permalinks as serving the address.



    * Cover unreadable and invalid UCP discovery files in the fix test



    * Agent readiness: name the permalink step as in the design, and the connection URL when a file is the cause

    * Agent readiness: say store details and connection URL in the UCP file fixes, and Change permalinks on the button

diff --git a/plugins/woocommerce/changelog/fix-agent-readiness-plain-permalinks b/plugins/woocommerce/changelog/fix-agent-readiness-plain-permalinks
new file mode 100644
index 00000000000..7f03b1b92ce
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-agent-readiness-plain-permalinks
@@ -0,0 +1,4 @@
+Significance: patch
+Type: dev
+Comment: Agent readiness explains how to make the UCP address reachable; behind a hidden flag.
+
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
index 15e37e1dec7..26e051a9ef7 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/AgenticCommerceSettingsPage.php
@@ -819,10 +819,19 @@ class AgenticCommerceSettingsPage extends \WC_Settings_Page {
 	 * What an open check asks the merchant to do: the action, the button text and where it goes.
 	 * A policy page that is chosen but not published links to its editor; a published store page asks for another page.
 	 *
-	 * @param array{id:string,label:string,fix_url:string} $check Store condition.
+	 * @param array{id:string,label:string,fix?:string,fix_url:string} $check Store condition.
 	 * @return array{0:string,1:string,2:string}
 	 */
 	private function check_action( array $check ): array {
+		// The UCP row's text is the specific fix (delete the file, fix permissions, or change permalinks).
+		if ( 'ucp_discovery' === $check['id'] ) {
+			$fix = (string) ( $check['fix'] ?? '' );
+			return array(
+				'' !== $fix ? $fix : __( 'Fix your connection URL', 'woocommerce' ),
+				__( 'Change permalinks', 'woocommerce' ),
+				(string) ( $check['fix_url'] ?? '' ),
+			);
+		}
 		$policies = array(
 			'privacy_page'         => array( AgenticCommerceSettings::PRIVACY_PAGE_OPTION, __( 'Publish your privacy policy page', 'woocommerce' ), __( 'Choose a privacy policy page', 'woocommerce' ) ),
 			'terms_page'           => array( AgenticCommerceSettings::TERMS_PAGE_OPTION, __( 'Publish your terms and conditions page', 'woocommerce' ), __( 'Choose a terms and conditions page', 'woocommerce' ) ),
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/README.md b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
index 9d97e663efc..0ea2e7e975a 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/README.md
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/README.md
@@ -52,7 +52,7 @@ Only published simple and variable products are checked, the types agents suppor
 - Products hidden from the shop catalog (catalog visibility "Search results only" or "Hidden"). Agents see the products shoppers see in the shop, so hiding one is the merchant's choice, not a problem.
 - Products of any other type: grouped, external, subscription, booking, bundle and so on. A product keeps its stored type when its plugin is inactive, so it stays in this group.

-Store-wide conditions (`StoreConditions`) are reported first because they affect every product: coming soon mode and "Discourage search engines" hide the products, UCP off and no HTTPS hide the catalog from UCP agents, and guest checkout off or no payment method turned on stops agents placing orders. Missing policy pages and order emails off weaken agent orders. Each condition's `blocks` says which, so a reader can tell a hidden store from one agents can't buy from.
+Store-wide conditions (`StoreConditions`) are reported first because they affect every product: coming soon mode and "Discourage search engines" hide the products, UCP off, no HTTPS and a `/.well-known/ucp` the store can't serve (Plain permalinks without a static file, a file WooCommerce didn't write in the way, or WooCommerce's file with an outdated profile; see `UcpDiscovery::serve_status()`, which picks the fix shown) hide the catalog from UCP agents, and guest checkout off or no payment method turned on stops agents placing orders. Missing policy pages and order emails off weaken agent orders. Each condition's `blocks` says which, so a reader can tell a hidden store from one agents can't buy from.

 ## Store output checks

@@ -205,7 +205,7 @@ WooCommerce > Settings > Agentic commerce (`AgenticCommerceSettings`, `AgenticCo

 - The UCP switch, first. It saves through `POST wc/v3/agent-readiness/ucp` (`{ "enabled": true }`). A failing required check keeps it from being turned on, and that POST answers 409; turning it off still works. In coming soon mode the card says agents can't shop the store yet and links to Site visibility.
 - Product counts from the stored report (`products`, `hidden_from_catalog`, `unsupported_types`), each linking to a filtered product list.
-- Status: the store conditions from `StoreConditions`, the same list the readiness report shows, in three groups. Required lists failing `required` conditions (coming soon mode and HTTPS) and puts the status at Action needed; Recommended lists failing `recommended` ones, such as a missing privacy, terms, refund and returns, or shipping policy page (policy pages are not required by the UCP spec); Done lists the passing ones by their passing state (`name`). Each open condition says what to do and links to it; a chosen policy page that isn't published links to its editor.
+- Status: the store conditions from `StoreConditions`, the same list the readiness report shows, in three groups. Required lists failing `required` conditions (coming soon mode, HTTPS and the UCP address) and puts the status at Action needed; Recommended lists failing `recommended` ones, such as a missing privacy, terms, refund and returns, or shipping policy page (policy pages are not required by the UCP spec); Done lists the passing ones by their passing state (`name`). Each open condition says what to do and links to the screen that does it, when there is one. The UCP address row names the file to remove or the folder permissions to change, and links to permalinks only when changing them is one of the fixes. A chosen policy page that isn't published links to its editor.
 - Agent readiness: the store output checks from the stored report, since they only run in the scan. Each check names the question it answers in `group` (`access`, `find`, `understand` or `buy`), and the card shows the checks under those four questions. They are never required, so they don't affect the switch or Status. A failing row adds why it matters and what it affects (`blocks`). The card has "Run check" with the time of the last run, and the product checks from the stored report: per-channel counts, and each failing check with its channels and up to 3 example products. The stored report still keeps up to 10 ids per check.
 - Store policy pages. Refund and returns, privacy and terms are the existing options, so they stay in sync with Advanced > Page setup and Settings > Privacy; shipping policy, FAQ and warranty are new. They are for the policy links a UCP checkout can carry (`links`); the UCP endpoints don't send them yet. The dropdowns list published pages other than the cart, checkout, shop and My account pages, and saving leaves a stored page in place even when it's a draft or one of those store pages, which then fails its check.
 - The store address agents start from (`/.well-known/ucp`), with Copy.
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php b/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
index 3227b57e743..a3c5fb08a2a 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/StoreConditions.php
@@ -4,6 +4,7 @@ declare( strict_types = 1 );
 namespace Automattic\WooCommerce\Internal\AgentReadiness;

 use Automattic\WooCommerce\Internal\ComingSoon\ComingSoonHelper;
+use Automattic\WooCommerce\Internal\Ucp\UcpDiscovery;
 use Automattic\WooCommerce\StoreApi\Utilities\Ucp\Utils;

 defined( 'ABSPATH' ) || exit;
@@ -111,6 +112,7 @@ class StoreConditions {
 				'fix'     => __( 'Move the site to HTTPS; your host can usually turn it on.', 'woocommerce' ),
 				'fix_url' => wp_get_update_https_url(),
 			),
+			self::ucp_discovery( UcpDiscovery::serve_status() ),
 			$policy_page(
 				'privacy_page',
 				AgenticCommerceSettings::PRIVACY_PAGE_OPTION,
@@ -175,6 +177,28 @@ class StoreConditions {
 		);
 	}

+	/**
+	 * The UCP address condition, with the fix for why the address doesn't serve the profile.
+	 *
+	 * @param string $status A status from UcpDiscovery::serve_status().
+	 * @return array{id:string,ok:bool,blocks:string,level:string,name:string,label:string,why:string,fix:string,fix_url:string}
+	 */
+	private static function ucp_discovery( string $status ): array {
+		return array(
+			'id'      => 'ucp_discovery',
+			'ok'      => 'ok' === $status,
+			'blocks'  => 'ucp',
+			'level'   => self::LEVEL_REQUIRED,
+			'name'    => __( 'Use a readable permalink structure', 'woocommerce' ),
+			// Without a file in the way, Plain permalinks are why the connection URL doesn't load.
+			'label'   => 'no_file' === $status ? __( 'Use a readable permalink structure', 'woocommerce' ) : __( 'Fix your connection URL', 'woocommerce' ),
+			'why'     => 'no_file' === $status ? __( 'Any structure except Plain lets AI assistants reach your store.', 'woocommerce' ) : __( 'AI assistants use your connection URL to find your products, and it doesn\'t load your store\'s details.', 'woocommerce' ),
+			'fix'     => UcpDiscovery::discovery_fix( $status ),
+			// Permalinks are one fix only when nothing is serving the address. A file in the way is removed on disk.
+			'fix_url' => 'no_file' === $status ? admin_url( 'options-permalink.php' ) : '',
+		);
+	}
+
 	/**
 	 * Ids of the required conditions that fail.
 	 *
diff --git a/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php b/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
index 4fe4560e024..5a0d54d7f7d 100644
--- a/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
+++ b/plugins/woocommerce/src/Internal/AgentReadiness/UcpSwitch.php
@@ -4,6 +4,7 @@ declare( strict_types = 1 );
 namespace Automattic\WooCommerce\Internal\AgentReadiness;

 use Automattic\WooCommerce\Internal\Features\FeaturesController;
+use Automattic\WooCommerce\Internal\Ucp\UcpDiscovery;
 use Automattic\WooCommerce\StoreApi\Utilities\Ucp\Utils as UcpUtils;

 defined( 'ABSPATH' ) || exit;
@@ -37,6 +38,13 @@ class UcpSwitch {
 	 */
 	private StoreConditions $store_conditions;

+	/**
+	 * UCP discovery file.
+	 *
+	 * @var UcpDiscovery
+	 */
+	private UcpDiscovery $ucp_discovery;
+
 	/**
 	 * Initialize dependencies.
 	 *
@@ -44,10 +52,12 @@ class UcpSwitch {
 	 *
 	 * @param FeaturesController $features_controller Features controller.
 	 * @param StoreConditions    $store_conditions    Store conditions.
+	 * @param UcpDiscovery       $ucp_discovery       UCP discovery file.
 	 */
-	final public function init( FeaturesController $features_controller, StoreConditions $store_conditions ): void {
+	final public function init( FeaturesController $features_controller, StoreConditions $store_conditions, UcpDiscovery $ucp_discovery ): void {
 		$this->features_controller = $features_controller;
 		$this->store_conditions    = $store_conditions;
+		$this->ucp_discovery       = $ucp_discovery;
 	}

 	/**
@@ -70,6 +80,10 @@ class UcpSwitch {

 		if ( UcpUtils::is_enabled() !== $enable ) {
 			$this->features_controller->change_feature_enable( UcpUtils::FEATURE_ID, $enable );
+			// Plain and index.php permalinks are served from the static file. Write it now so the address exists as soon as UCP is on.
+			if ( $enable ) {
+				$this->ucp_discovery->maybe_sync_file();
+			}
 			\WC_Tracks::record_event( 'agentic_commerce_ucp_toggled', array( 'enabled' => $enable ? 'yes' : 'no' ) );
 		}

diff --git a/plugins/woocommerce/src/Internal/Ucp/UcpDiscovery.php b/plugins/woocommerce/src/Internal/Ucp/UcpDiscovery.php
index 91b9529a1c7..183b05ab70a 100644
--- a/plugins/woocommerce/src/Internal/Ucp/UcpDiscovery.php
+++ b/plugins/woocommerce/src/Internal/Ucp/UcpDiscovery.php
@@ -42,6 +42,84 @@ final class UcpDiscovery implements RegisterHooksInterface {
 		add_action( 'init', array( $this, 'register_feature_hooks' ), 0, 0 );
 	}

+	/**
+	 * Why `/.well-known/ucp` does or doesn't serve WooCommerce's current profile, from the
+	 * permalink setting and the static file, read on every call so nothing is stored.
+	 *
+	 * Plain permalinks, and structures that start with index.php, don't route that address.
+	 * Before UCP is on, a folder WooCommerce can write still counts as ok: turning UCP on writes the file.
+	 *
+	 * @return string One of `ok`, `no_file`, `file_in_the_way`, `not_readable`, `file_unusable`, `file_outdated`.
+	 */
+	public static function serve_status(): string {
+		$path = self::get_file_path();
+		if ( ! is_file( $path ) ) {
+			if ( self::rewrite_serves_discovery() ) {
+				return 'ok';
+			}
+			// UCP off and a writable folder: enabling UCP writes the file, so permalinks don't have to change.
+			if ( ! Utils::is_enabled() && self::can_create_file( $path ) ) {
+				return 'ok';
+			}
+			return 'no_file';
+		}
+
+		if ( ! is_readable( $path ) ) {
+			return 'not_readable';
+		}
+
+		// The profile is a few KB; cap the read so a large file someone else put there isn't read whole.
+		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
+		$profile = json_decode( (string) file_get_contents( $path, false, null, 0, 65536 ), true );
+		if ( ! is_array( $profile ) ) {
+			return 'file_unusable';
+		}
+
+		$links = $profile['links'] ?? null;
+		if ( ! is_array( $links ) || ! in_array( self::LINK_REL, array_column( $links, 'rel' ), true ) ) {
+			return 'file_in_the_way';
+		}
+
+		// Compare the decoded `ucp` part, not the raw text, so formatting and the ownership link don't matter.
+		// The current profile goes through the same JSON round trip, so objects and arrays compare alike.
+		$current = json_decode( (string) wp_json_encode( ( new self() )->get_profile()['ucp'] ), true );
+		return ( $profile['ucp'] ?? null ) === $current ? 'ok' : 'file_outdated';
+	}
+
+	/**
+	 * What a merchant should do for a failing serve_status() value. Includes the file path.
+	 *
+	 * @param string $status A status from serve_status().
+	 * @return string Empty when the address is already served.
+	 */
+	public static function discovery_fix( string $status ): string {
+		$path = self::get_file_path();
+		$dir  = dirname( $path );
+
+		switch ( $status ) {
+			case 'not_readable':
+				/* translators: 1: discovery file path, 2: folder path. */
+				return sprintf( __( 'WooCommerce can\'t read %1$s. Make that file readable by the web server, or delete it. If you can\'t delete it, make %2$s writable by the web server.', 'woocommerce' ), $path, $dir );
+			case 'file_unusable':
+				/* translators: 1: discovery file path, 2: folder path. */
+				return sprintf( __( 'The %1$s file is incomplete or damaged, so your connection URL can give AI assistants wrong details. Delete it and check the server has free disk space. If you can\'t delete it, make %2$s writable by the web server.', 'woocommerce' ), $path, $dir );
+			case 'file_in_the_way':
+				/* translators: 1: discovery file path, 2: folder path. */
+				return sprintf( __( 'Remove the %1$s file that WooCommerce didn\'t write. It loads instead of your store\'s details. If you can\'t remove it, make %2$s writable by the web server.', 'woocommerce' ), $path, $dir );
+			case 'file_outdated':
+				/* translators: 1: discovery file path, 2: folder path. */
+				return sprintf( __( 'Delete the %1$s file. It has old store details. If you can\'t delete it, make %2$s writable by the web server so WooCommerce can replace it.', 'woocommerce' ), $path, $dir );
+			case 'no_file':
+				if ( is_multisite() ) {
+					return __( 'Choose any structure except Plain under Settings > Permalinks. Structures that start with index.php don\'t work either.', 'woocommerce' );
+				}
+				/* translators: %s: folder path. */
+				return sprintf( __( 'Choose any structure except Plain under Settings > Permalinks. Structures that start with index.php don\'t work either. Or make %s writable by the web server so WooCommerce can write the file.', 'woocommerce' ), $dir );
+			default:
+				return '';
+		}
+	}
+
 	/**
 	 * Register the renderer, plus the rewrite rule when pretty permalinks are on, when UCP is enabled.
 	 */
@@ -107,20 +185,19 @@ final class UcpDiscovery implements RegisterHooksInterface {
 	}

 	/**
-	 * Keep the static discovery file in sync on admin screens: write it under plain permalinks, delete it under pretty ones.
-	 * The file only refreshes on admin page loads.
+	 * Keep the static discovery file in sync: write it when permalinks don't route `/.well-known/ucp`
+	 * (Plain, or a structure that starts with index.php), and delete it when they do.
+	 * The file only refreshes on admin page loads, and when UCP is turned on.
 	 *
 	 * Failures are silent here: the Agentic Readiness checks report an unreachable or invalid discovery endpoint.
 	 */
 	public function maybe_sync_file(): void {
-		global $wp_rewrite;
-
 		// admin_init also fires for anonymous admin-ajax.php/admin-post.php requests and on every heartbeat.
 		if ( wp_doing_ajax() || ! current_user_can( 'manage_woocommerce' ) ) {
 			return;
 		}

-		if ( $wp_rewrite->using_permalinks() ) {
+		if ( self::rewrite_serves_discovery() ) {
 			// A file that cannot be deleted keeps overriding the profile WooCommerce serves, as the web server answers first.
 			$this->delete_file();
 			return;
@@ -175,12 +252,50 @@ final class UcpDiscovery implements RegisterHooksInterface {
 		return is_array( $links ) && in_array( self::LINK_REL, array_column( $links, 'rel' ), true );
 	}

+	/**
+	 * Whether the permalink structure routes `/.well-known/ucp` to WordPress.
+	 * Structures that start with index.php (PATHINFO) do not: the web server only does
+	 * when it sends every path to WordPress, and the static file covers that case.
+	 *
+	 * @return bool
+	 */
+	private static function rewrite_serves_discovery(): bool {
+		global $wp_rewrite;
+
+		return $wp_rewrite->using_mod_rewrite_permalinks();
+	}
+
+	/**
+	 * Whether WooCommerce can create the static file, including the `.well-known` folder.
+	 * One file under ABSPATH can't hold a profile per site, so multisite never can.
+	 *
+	 * @param string $path Absolute file path.
+	 * @return bool
+	 */
+	private static function can_create_file( string $path ): bool {
+		if ( is_multisite() ) {
+			return false;
+		}
+
+		$dir = dirname( $path );
+		while ( ! is_dir( $dir ) ) {
+			$parent = dirname( $dir );
+			if ( $parent === $dir ) {
+				return false;
+			}
+			$dir = $parent;
+		}
+
+		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+		return is_writable( $dir );
+	}
+
 	/**
 	 * Path of the static discovery file served under plain permalinks.
 	 *
 	 * @return string
 	 */
-	private function get_file_path(): string {
+	private static function get_file_path(): string {
 		/**
 		 * Filters the path of the static UCP discovery file written when plain permalinks are active.
 		 *
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
index d636084bdad..8391190ae57 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/AgenticCommerceSettingsTest.php
@@ -640,6 +640,59 @@ class AgenticCommerceSettingsTest extends WC_Unit_Test_Case {
 		$this->assertSame( $privacy, (int) get_option( AgenticCommerceSettings::PRIVACY_PAGE_OPTION ) );
 	}

+	/**
+	 * @testdox A discovery file WooCommerce didn't write shows the removal instruction, not a permalinks link.
+	 */
+	public function test_ucp_file_in_the_way_shows_the_removal_instruction(): void {
+		StoreConditionsTest::make_store_ready();
+		$path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/.well-known/ucp';
+		wp_mkdir_p( dirname( $path ) );
+		file_put_contents( $path, '{}' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+
+		try {
+			$html = $this->render_page();
+			$this->assertStringContainsString( 'didn&#039;t write', $html );
+			$this->assertStringContainsString( esc_html( $path ), $html );
+			$this->assertStringNotContainsString( 'options-permalink.php', $html );
+			$this->assertStringNotContainsString( 'Change permalinks', $html );
+		} finally {
+			wp_delete_file( $path );
+			foreach ( array( dirname( $path ), dirname( $path, 2 ) ) as $dir ) {
+				if ( is_dir( $dir ) ) {
+					rmdir( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+				}
+			}
+		}
+	}
+
+	/**
+	 * @testdox When the discovery file can't be written, the status row says to change permalinks or make the folder writable.
+	 */
+	public function test_ucp_no_file_shows_permalink_and_permission_fixes(): void {
+		global $wp_rewrite;
+		StoreConditionsTest::make_store_ready();
+		$wp_rewrite->set_permalink_structure( '' );
+		$locked = get_temp_dir() . uniqid( 'wc-ucp-locked-' );
+		mkdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
+		chmod( $locked, 0555 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $locked . '/ucp' );
+
+		try {
+			if ( is_writable( $locked ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+				$this->markTestSkipped( 'The test runs as a user who can write any directory (root).' );
+			}
+			$html = $this->render_page();
+			$this->assertStringContainsString( 'Change permalinks', $html );
+			$this->assertStringContainsString( 'options-permalink.php', $html );
+			$this->assertStringContainsString( 'writable', $html );
+			$this->assertStringContainsString( 'index.php', $html );
+		} finally {
+			chmod( $locked, 0755 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			rmdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+		}
+	}
+
 	/**
 	 * @testdox The switch stays disabled until the required checks pass.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
index 20ddd7fe1d7..6a05ec6d2ac 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessChecksTest.php
@@ -488,6 +488,7 @@ class ReadinessChecksTest extends WC_Unit_Test_Case {
 				'search_visible'       => 'listing',
 				'ucp_on'               => 'ucp',
 				'https'                => 'ucp',
+				'ucp_discovery'        => 'ucp',
 				'privacy_page'         => 'checkout',
 				'terms_page'           => 'checkout',
 				'refund_returns_page'  => 'checkout',
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
index 7a5c0e3cf1a..d7878d51949 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/ReadinessRestControllerTest.php
@@ -6,6 +6,7 @@ namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;
 use Automattic\WooCommerce\Internal\AgentReadiness\AgentReadiness;
 use Automattic\WooCommerce\Internal\AgentReadiness\ScheduledScan;
 use Automattic\WooCommerce\Internal\AgentReadiness\UcpSwitch;
+use Automattic\WooCommerce\Internal\Ucp\UcpDiscovery;
 use WC_REST_Unit_Test_Case;
 use WP_REST_Request;

@@ -195,6 +196,31 @@ class ReadinessRestControllerTest extends WC_REST_Unit_Test_Case {
 		$this->assertSame( 'no', get_option( 'woocommerce_feature_ucp_enabled' ) );
 	}

+	/**
+	 * @testdox Turning UCP on with Plain permalinks writes the discovery file, so the address is served without a permalink change.
+	 */
+	public function test_turning_ucp_on_writes_the_discovery_file_for_plain_permalinks(): void {
+		global $wp_rewrite;
+		StoreConditionsTest::make_store_ready();
+		$wp_rewrite->set_permalink_structure( '' );
+		$path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/ucp';
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+
+		try {
+			$response = $this->dispatch_ucp( true );
+
+			$this->assertSame( 200, $response->get_status() );
+			$this->assertFileExists( $path );
+			$this->assertSame( 'ok', UcpDiscovery::serve_status() );
+		} finally {
+			wp_delete_file( $path );
+			$dir = dirname( $path );
+			if ( is_dir( $dir ) ) {
+				rmdir( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+			}
+		}
+	}
+
 	/**
 	 * @testdox A user without manage_woocommerce can't switch UCP.
 	 */
diff --git a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
index c9b7c0dbb2a..3e5e0103778 100644
--- a/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/AgentReadiness/StoreConditionsTest.php
@@ -5,6 +5,7 @@ namespace Automattic\WooCommerce\Tests\Internal\AgentReadiness;

 use Automattic\WooCommerce\Internal\AgentReadiness\AgenticCommerceSettings;
 use Automattic\WooCommerce\Internal\AgentReadiness\StoreConditions;
+use Automattic\WooCommerce\Internal\Ucp\UcpDiscovery;
 use WC_Unit_Test_Case;

 /**
@@ -175,10 +176,109 @@ class StoreConditionsTest extends WC_Unit_Test_Case {
 	}

 	/**
-	 * Make every required check pass: the store is launched and the home URL is HTTPS.
+	 * @testdox Plain permalinks pass when WooCommerce can write the discovery file, and fail with both fixes when it can't.
+	 */
+	public function test_plain_permalinks_depend_on_writing_the_discovery_file(): void {
+		global $wp_rewrite;
+		self::make_store_ready();
+		$wp_rewrite->set_permalink_structure( '' );
+
+		$this->assertNotContains( 'ucp_discovery', $this->sut->failing_required() );
+
+		$locked = get_temp_dir() . uniqid( 'wc-ucp-locked-' );
+		mkdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
+		chmod( $locked, 0555 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $locked . '/ucp' );
+		try {
+			if ( is_writable( $locked ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+				$this->markTestSkipped( 'The test runs as a user who can write any directory (root).' );
+			}
+			$this->assertSame( array( 'ucp_discovery' ), $this->sut->failing_required() );
+			$fix = $this->ucp_discovery_fix();
+			$this->assertStringContainsString( 'Settings > Permalinks', $fix );
+			$this->assertStringContainsString( 'writable', $fix );
+			$checks = array_column( $this->sut->all(), null, 'id' );
+			$this->assertSame( admin_url( 'options-permalink.php' ), $checks['ucp_discovery']['fix_url'] );
+			$this->assertSame( 'Use a readable permalink structure', $checks['ucp_discovery']['label'], 'Plain permalinks are the cause, so the step names them' );
+		} finally {
+			chmod( $locked, 0755 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			rmdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+		}
+	}
+
+	/**
+	 * @testdox A /.well-known/ucp file in the way fails the UCP address check with the fix for its reason, and deleting it passes the check.
+	 * @testWith ["foreign", "Remove the "]
+	 *           ["outdated", "Delete the "]
+	 *           ["not_json", "The "]
+	 *           ["unreadable", "WooCommerce can't read "]
+	 *
+	 * @param string $file   Someone else's file, an old profile, invalid JSON, or a file the web server can't read.
+	 * @param string $prefix How the fix should start.
+	 */
+	public function test_ucp_file_fix( string $file, string $prefix ): void {
+		self::make_store_ready();
+		$path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/.well-known/ucp';
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+
+		$profile                   = ( new UcpDiscovery() )->get_profile();
+		$profile['ucp']['version'] = '1999-01-01';
+		$encoded                   = (string) wp_json_encode( $profile );
+		$contents                  = array(
+			'foreign'    => '{}',
+			'outdated'   => $encoded,
+			'not_json'   => '{bad',
+			'unreadable' => $encoded,
+		);
+
+		wp_mkdir_p( dirname( $path ) );
+		file_put_contents( $path, $contents[ $file ] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+		if ( 'unreadable' === $file ) {
+			chmod( $path, 0000 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+		}
+
+		try {
+			if ( 'unreadable' === $file && is_readable( $path ) ) {
+				$this->markTestSkipped( 'The test runs as a user who can read any file (root).' );
+			}
+			$this->assertSame( array( 'ucp_discovery' ), $this->sut->failing_required() );
+			$this->assertStringStartsWith( $prefix, $this->ucp_discovery_fix() );
+			$this->assertStringContainsString( $path, $this->ucp_discovery_fix() );
+			$checks = array_column( $this->sut->all(), null, 'id' );
+			$this->assertSame( '', $checks['ucp_discovery']['fix_url'] );
+			$this->assertSame( 'Fix your connection URL', $checks['ucp_discovery']['label'], 'A file is the cause, not permalinks' );
+
+			// Following the fix passes the check: with the file gone and pretty permalinks, nothing is in the way.
+			if ( 'unreadable' === $file ) {
+				chmod( $path, 0644 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			}
+			wp_delete_file( $path );
+			$this->assertSame( array(), $this->sut->failing_required() );
+		} finally {
+			if ( is_file( $path ) ) {
+				chmod( $path, 0644 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			}
+			self::remove_ucp_file( $path );
+		}
+	}
+
+	/**
+	 * The fix text the UCP address check shows now.
+	 *
+	 * @return string
+	 */
+	private function ucp_discovery_fix(): string {
+		$checks = array_column( $this->sut->all(), null, 'id' );
+		return $checks['ucp_discovery']['fix'];
+	}
+
+	/**
+	 * Make every required check pass: the store is launched, the home URL is HTTPS and permalinks aren't Plain.
 	 * Privacy, terms and the refund page are set so those checks count as done.
 	 */
 	public static function make_store_ready(): void {
+		global $wp_rewrite;
+		$wp_rewrite->set_permalink_structure( '/%postname%/' );
 		add_filter( 'pre_option_home', static fn() => 'https://example.org' );
 		update_option( 'woocommerce_coming_soon', 'no' );
 		$page = wp_insert_post(
@@ -192,4 +292,18 @@ class StoreConditionsTest extends WC_Unit_Test_Case {
 			update_option( $option, $page );
 		}
 	}
+
+	/**
+	 * Delete a test discovery file and the two folders created for it.
+	 *
+	 * @param string $path File path under a `wc-ucp-*` temp folder.
+	 */
+	private static function remove_ucp_file( string $path ): void {
+		wp_delete_file( $path );
+		foreach ( array( dirname( $path ), dirname( $path, 2 ) ) as $dir ) {
+			if ( is_dir( $dir ) ) {
+				rmdir( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+			}
+		}
+	}
 }
diff --git a/plugins/woocommerce/tests/php/src/Internal/Ucp/UcpDiscoveryTest.php b/plugins/woocommerce/tests/php/src/Internal/Ucp/UcpDiscoveryTest.php
index 197b6210a6f..50b6ea1e8bd 100644
--- a/plugins/woocommerce/tests/php/src/Internal/Ucp/UcpDiscoveryTest.php
+++ b/plugins/woocommerce/tests/php/src/Internal/Ucp/UcpDiscoveryTest.php
@@ -102,6 +102,116 @@ class UcpDiscoveryTest extends \WC_Unit_Test_Case {
 		$this->assertSame( 'yes', get_option( 'woocommerce_queue_flush_rewrite_rules' ) );
 	}

+	/**
+	 * @testdox serve_status reads the permalink setting and the static file: no file is fine with permalinks WordPress routes, and with Plain or index.php permalinks before UCP is on when the file can be written; a file must be WooCommerce's and current.
+	 * @testWith ["/%postname%/", null, "ok"]
+	 *           ["/%postname%/", "current", "ok"]
+	 *           ["/%postname%/", "foreign", "file_in_the_way"]
+	 *           ["/%postname%/", "outdated", "file_outdated"]
+	 *           ["", null, "ok"]
+	 *           ["", "current", "ok"]
+	 *           ["", "current, other formatting", "ok"]
+	 *           ["", "foreign", "file_in_the_way"]
+	 *           ["", "not json", "file_unusable"]
+	 *           ["", "cut short", "file_unusable"]
+	 *           ["", "outdated", "file_outdated"]
+	 *           ["/index.php/%postname%/", null, "ok"]
+	 *           ["/index.php/%postname%/", "current", "ok"]
+	 *           ["/index.php/%postname%/", "foreign", "file_in_the_way"]
+	 *
+	 * @param string      $structure Permalink structure.
+	 * @param string|null $file      The static file, or null for none.
+	 * @param string      $expected  Expected status.
+	 */
+	public function test_serve_status( string $structure, ?string $file, string $expected ): void {
+		$path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/.well-known/ucp';
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+		$this->set_permalink_structure( $structure );
+		if ( null !== $file ) {
+			$ours    = $this->sut->get_profile();
+			$old     = $ours;
+			$foreign = $ours;
+
+			$foreign['links'] = array( $ours['links'][0] );
+
+			$old['ucp']['services']['dev.ucp.shopping'][0]['endpoint'] = 'http://old.example/wp-json/wc/ucp/v1';
+
+			$current  = (string) wp_json_encode( $ours, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
+			$contents = array(
+				'current'                   => $current,
+				'current, other formatting' => (string) wp_json_encode( $ours ),
+				'foreign'                   => (string) wp_json_encode( $foreign ),
+				'outdated'                  => (string) wp_json_encode( $old ),
+				'not json'                  => 'not json',
+				'cut short'                 => substr( $current, 0, (int) ( strlen( $current ) / 2 ) ),
+			);
+			wp_mkdir_p( dirname( $path ) );
+			file_put_contents( $path, $contents[ $file ] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+		}
+
+		try {
+			$this->assertSame( $expected, UcpDiscovery::serve_status() );
+		} finally {
+			self::remove_ucp_file( $path );
+		}
+	}
+
+	/**
+	 * @testdox serve_status counts a file it can't read as in the way, even when it holds WooCommerce's current profile.
+	 */
+	public function test_serve_status_unreadable_file(): void {
+		$path = get_temp_dir() . uniqid( 'wc-ucp-' ) . '/.well-known/ucp';
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $path );
+		$this->set_permalink_structure( '' );
+
+		wp_mkdir_p( dirname( $path ) );
+		file_put_contents( $path, (string) wp_json_encode( $this->sut->get_profile() ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
+		chmod( $path, 0000 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+
+		try {
+			if ( is_readable( $path ) ) {
+				$this->markTestSkipped( 'The test runs as a user who can read any file (root).' );
+			}
+			$this->assertSame( 'not_readable', UcpDiscovery::serve_status() );
+		} finally {
+			chmod( $path, 0644 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			self::remove_ucp_file( $path );
+		}
+	}
+
+	/**
+	 * @testdox Plain and index.php permalinks are not ok once UCP is on without a file, or when the folder can't be written.
+	 */
+	public function test_serve_status_no_file_when_the_address_cannot_be_served(): void {
+		update_option( 'woocommerce_feature_ucp_enabled', 'yes' );
+		$this->set_permalink_structure( '' );
+		$this->assertSame( 'no_file', UcpDiscovery::serve_status() );
+
+		$this->set_permalink_structure( '/index.php/%postname%/' );
+		$this->assertSame( 'no_file', UcpDiscovery::serve_status(), 'A structure starting with index.php does not route /.well-known/ucp' );
+
+		update_option( 'woocommerce_feature_ucp_enabled', 'no' );
+		$locked = get_temp_dir() . uniqid( 'wc-ucp-locked-' );
+		mkdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
+		chmod( $locked, 0555 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+		add_filter( 'woocommerce_ucp_discovery_file_path', fn() => $locked . '/ucp' );
+		try {
+			if ( is_writable( $locked ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
+				$this->markTestSkipped( 'The test runs as a user who can write any directory (root).' );
+			}
+			$this->set_permalink_structure( '' );
+			$this->assertSame( 'no_file', UcpDiscovery::serve_status() );
+			$fix = UcpDiscovery::discovery_fix( 'no_file' );
+			$this->assertStringContainsString( 'Settings > Permalinks', $fix );
+			$this->assertStringContainsString( 'index.php', $fix );
+			$this->assertStringContainsString( 'writable', $fix );
+			$this->assertStringContainsString( $locked, $fix );
+		} finally {
+			chmod( $locked, 0755 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
+			rmdir( $locked ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+		}
+	}
+
 	/**
 	 * @testdox The static file is written under plain permalinks, removed under pretty ones, and removed when UCP is turned off or WooCommerce is deactivated.
 	 */
@@ -114,6 +224,11 @@ class UcpDiscoveryTest extends \WC_Unit_Test_Case {
 		$this->sut->maybe_sync_file();
 		$this->assertFileDoesNotExist( $this->file );

+		$this->set_permalink_structure( '/index.php/%postname%/' );
+		$this->sut->maybe_sync_file();
+		$this->assertFileExists( $this->file, 'PATHINFO permalinks are served from the static file' );
+		wp_delete_file( $this->file );
+
 		$this->set_permalink_structure( '' );
 		$this->sut->maybe_sync_file();
 		$this->sut->maybe_flush_rewrite_rules( Utils::FEATURE_ID, false );
@@ -238,4 +353,18 @@ class UcpDiscoveryTest extends \WC_Unit_Test_Case {
 	public function test_maybe_render_ignores_other_requests( string $matched_rule, string $query_var ): void {
 		$this->assertNull( $this->render( $matched_rule, $query_var ) );
 	}
+
+	/**
+	 * Delete a test discovery file and the two folders created for it.
+	 *
+	 * @param string $path File path under a `wc-ucp-*` temp folder.
+	 */
+	private static function remove_ucp_file( string $path ): void {
+		wp_delete_file( $path );
+		foreach ( array( dirname( $path ), dirname( $path, 2 ) ) as $dir ) {
+			if ( is_dir( $dir ) ) {
+				rmdir( $dir ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
+			}
+		}
+	}
 }