From b6ebd11317c74680f716d25aa31af0c0e77765fd Mon Sep 17 00:00:00 2001 From: Mwale Kalenga Date: Wed, 14 Oct 2026 12:03:24 +1100 Subject: [PATCH 1/3] Let plugins add notices to posts and stop agent writes Adds gk/block-mcp/post/notices (shown as notices on get_page_blocks, get_post_info and resolve_url) and gk/block-mcp/post/pre-write (refuse a block edit, update_post or Yoast write with a message). Both run inside the controller and Post_Manager, so they hold on the REST and Abilities transports. A notices callback that throws is skipped; a pre-write callback that throws refuses the write. --- .../tools/read/get_page_blocks.test.ts | 23 ++ src/agent-guide.ts | 4 + src/tools/discovery.ts | 4 +- src/tools/read.ts | 5 +- .../includes/class-post-extensions.php | 161 ++++++++++ .../includes/class-post-manager.php | 5 + .../includes/class-rest-controller.php | 16 +- .../includes/class-yoast-bridge.php | 7 +- wordpress-plugin/gk-block-mcp/readme.txt | 7 + .../tests/Abilities/AbilityExecutionTest.php | 33 ++ .../tests/Integrations/YoastBridgeTest.php | 22 ++ .../tests/REST/PostExtensionsTest.php | 282 ++++++++++++++++++ 12 files changed, 564 insertions(+), 5 deletions(-) create mode 100644 wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php create mode 100644 wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php diff --git a/src/__tests__/tools/read/get_page_blocks.test.ts b/src/__tests__/tools/read/get_page_blocks.test.ts index dff53853..6f4fe222 100644 --- a/src/__tests__/tools/read/get_page_blocks.test.ts +++ b/src/__tests__/tools/read/get_page_blocks.test.ts @@ -200,3 +200,26 @@ describe('get_page_blocks — enrichment with legacy blocks', () => { expect(result.warnings.length).toBeGreaterThan(0); }); }); + +describe('get_page_blocks — notices from site plugins', () => { + let client: ReturnType; + beforeEach(() => { client = makeMockClient(); }); + + it('passes the server notices through to the agent', async () => { + client.getPageBlocks.mockResolvedValueOnce({ ...pageBlocksResponse, notices: ['Edit the staged copy #42 instead.'] }); + const result = await handleReadTool('get_page_blocks', { post_id: 1 }, client as any) as { notices: string[] }; + expect(result.notices).toEqual(['Edit the staged copy #42 instead.']); + }); + + it('passes notices through in summary_only mode', async () => { + client.getPageBlocks.mockResolvedValueOnce({ summary: pageBlocksResponse.summary, notices: ['Edit #42 instead.'] } as any); + const result = await handleReadTool('get_page_blocks', { post_id: 1, summary_only: true }, client as any) as { notices: string[] }; + expect(result.notices).toEqual(['Edit #42 instead.']); + }); + + it('returns an empty list from a server that sends no notices', async () => { + client.getPageBlocks.mockResolvedValueOnce({ ...pageBlocksResponse }); + const result = await handleReadTool('get_page_blocks', { post_id: 1 }, client as any) as { notices: string[] }; + expect(result.notices).toEqual([]); + }); +}); diff --git a/src/agent-guide.ts b/src/agent-guide.ts index da9a81c5..1a1876be 100644 --- a/src/agent-guide.ts +++ b/src/agent-guide.ts @@ -20,6 +20,10 @@ The MCP does this for you: If the user says "change X on https://example.com/some-page/", your first tool call should be \`get_page_blocks({ url: "...", search: "keyword" })\` or \`resolve_url({ url: "..." })\` — not a shell command. +## Notices: read them before editing + +\`get_page_blocks\`, \`get_post_info\` and \`resolve_url\` return \`notices\`: notes from this site's plugins about the post. A URL always resolves to the published page, so a notice may tell you the change belongs somewhere else, such as "a staged copy of this page is waiting; edit #123 instead". Follow it. A write a plugin refuses comes back as an error that says what to do instead. + ## Moving / reordering blocks NEVER do a move as separate \`insert_blocks\` + \`delete_block\` calls — if the delete is skipped or fails, the page ends up with an orphaned clone of the original. The atomic primitive is the \`move\` op on \`edit_block_tree\`: diff --git a/src/tools/discovery.ts b/src/tools/discovery.ts index 91add686..9025afbf 100644 --- a/src/tools/discovery.ts +++ b/src/tools/discovery.ts @@ -100,7 +100,7 @@ export const DISCOVERY_TOOLS = [ }, { name: 'resolve_url', - description: 'URL or path → post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL.', + description: 'URL or path → post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL. Read the returned `notices` before editing.', annotations: { ...READ_ANNOT, title: 'Resolve URL to post' }, inputSchema: { type: 'object' as const, @@ -127,7 +127,7 @@ export const DISCOVERY_TOOLS = [ }, { name: 'get_post_info', - description: 'Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count}`. Replaces wp eval / get_permalink() shell-outs.', + description: 'Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count, notices}`. Read `notices` before editing. Replaces wp eval / get_permalink() shell-outs.', annotations: { ...READ_ANNOT, title: 'Get post info' }, inputSchema: { type: 'object' as const, diff --git a/src/tools/read.ts b/src/tools/read.ts index 538db6d4..1ed4d4fa 100644 --- a/src/tools/read.ts +++ b/src/tools/read.ts @@ -17,7 +17,7 @@ export const READ_TOOLS = [ { name: 'get_page_blocks', description: - "Get a post's blocks. Pass post_id OR url (server resolves URL — don't shell out). Returns `{post_id, summary, blocks[], block_count, warnings}`. Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode (\"static\"|\"dynamic\"|\"dual\"), preference? (when non-preferred)}`. Refs survive sibling shifts — pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.", + "Get a post's blocks. Pass post_id OR url (server resolves URL — don't shell out). Returns `{post_id, summary, blocks[], block_count, warnings, notices}`. Read `notices` before editing: site plugins use them for facts like \"edit the staged copy #123 instead\". Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode (\"static\"|\"dynamic\"|\"dual\"), preference? (when non-preferred)}`. Refs survive sibling shifts — pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.", annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true, title: 'Get post blocks' }, outputSchema: { type: 'object', @@ -27,6 +27,7 @@ export const READ_TOOLS = [ blocks: { type: 'array' }, block_count: { type: 'number' }, warnings: { type: 'array' }, + notices: { type: 'array', items: { type: 'string' } }, }, }, inputSchema: { @@ -174,6 +175,7 @@ export async function handleReadTool( return { post_id: postId, summary: (response as { summary?: unknown }).summary, + notices: (response as { notices?: string[] }).notices ?? [], }; } @@ -188,6 +190,7 @@ export async function handleReadTool( blocks: enriched.blocks, block_count: enriched.blocks.length, warnings: enriched.warnings, + notices: (response as { notices?: string[] }).notices ?? [], ...(pagination !== undefined ? { pagination } : {}), }; } diff --git a/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php b/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php new file mode 100644 index 00000000..7261b643 --- /dev/null +++ b/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php @@ -0,0 +1,161 @@ + 500 ) + ); + } + + if ( ! is_wp_error( $result ) ) { + return true; + } + + $data = $result->get_error_data(); + if ( ! is_array( $data ) || ! isset( $data['status'] ) ) { + $result->add_data( array_merge( is_array( $data ) ? $data : array(), array( 'status' => 409 ) ) ); + } + + return $result; + } + + /** + * Log an extension that threw. + * + * @param string $hook Hook name. + * @param \Throwable $e What it threw. + * + * @return void + */ + private static function log( $hook, \Throwable $e ) { + if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Surfaces a broken third-party extension to the site owner. + error_log( sprintf( '[gk-block-mcp] A callback on %s threw %s: %s', $hook, get_class( $e ), $e->getMessage() ) ); + } + } +} diff --git a/wordpress-plugin/gk-block-mcp/includes/class-post-manager.php b/wordpress-plugin/gk-block-mcp/includes/class-post-manager.php index 335263b4..28f3bf94 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-post-manager.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-post-manager.php @@ -305,6 +305,11 @@ public function update_post( $post_id, array $args ) { ); } + $write_check = Post_Extensions::check_write( $post_id, 'post' ); + if ( is_wp_error( $write_check ) ) { + return $write_check; + } + // Per-post writes bucket (10/min). Shared with the existing block-level // write tools so updating a post and editing its blocks share the budget. $rate_check = $this->block_crud->check_rate_limit( $post_id, 'write' ); diff --git a/wordpress-plugin/gk-block-mcp/includes/class-rest-controller.php b/wordpress-plugin/gk-block-mcp/includes/class-rest-controller.php index 793b94cc..46fb4cc8 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-rest-controller.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-rest-controller.php @@ -1819,6 +1819,7 @@ public function resolve_url( $request ) { 'status' => $post->post_status, 'slug' => $post->post_name, 'edit_url' => get_edit_post_link( $post_id, 'raw' ), + 'notices' => Post_Extensions::notices( $post_id, 'resolve_url' ), ), 200 ); @@ -2061,6 +2062,7 @@ public function post_info( $request ) { ), 'mime_type' => $post->post_mime_type, 'comment_count' => (int) $post->comment_count, + 'notices' => Post_Extensions::notices( $post->ID, 'post_info' ), ), 200 ); @@ -2124,7 +2126,13 @@ public function get_post_blocks( $request ) { // Summary-only mode: skip the blocks payload entirely. $summary_only = (bool) $request->get_param( 'summary_only' ); if ( $summary_only ) { - return new \WP_REST_Response( array( 'summary' => $summary ), 200 ); + return new \WP_REST_Response( + array( + 'summary' => $summary, + 'notices' => Post_Extensions::notices( $post_id, 'blocks' ), + ), + 200 + ); } // Fields filter runs AFTER search to strip unneeded data. @@ -2168,6 +2176,7 @@ public function get_post_blocks( $request ) { $response = array( 'summary' => $summary, 'blocks' => $blocks, + 'notices' => Post_Extensions::notices( $post_id, 'blocks' ), ); if ( $is_search ) { $response['match_count'] = count( $blocks ); @@ -2901,6 +2910,11 @@ private function with_post_edit_context( \WP_REST_Request $request, callable $op return $perm_check; } + $write_check = Post_Extensions::check_write( $post_id, 'blocks' ); + if ( is_wp_error( $write_check ) ) { + return $write_check; + } + $if_match = $this->check_if_match_for_post( $post_id, $request ); if ( is_wp_error( $if_match ) ) { return $if_match; diff --git a/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php b/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php index e6c7abe1..6de4ab22 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php @@ -309,7 +309,12 @@ protected function read_fields( $post_id ) { * @return true|\WP_Error */ protected function write_fields( $post_id, array $fields ) { - $post_id = (int) $post_id; + $post_id = (int) $post_id; + $write_check = Post_Extensions::check_write( $post_id, 'seo' ); + if ( is_wp_error( $write_check ) ) { + return $write_check; + } + $field_map = self::field_map(); $array_fields = self::array_fields(); diff --git a/wordpress-plugin/gk-block-mcp/readme.txt b/wordpress-plugin/gk-block-mcp/readme.txt index 792ed339..c73fd3da 100644 --- a/wordpress-plugin/gk-block-mcp/readme.txt +++ b/wordpress-plugin/gk-block-mcp/readme.txt @@ -122,9 +122,16 @@ Visit Settings → Block MCP. Set the score for a namespace to less than 10 to m = develop = +#### 🚀 Added +* Other plugins can now show the assistant notes about a page, such as "a staged copy of this page is waiting; edit that instead", and can stop the assistant's edit to a page before it happens, with a message that says what to do instead. + #### 🔧 Updated * The minimum required WordPress version is now 6.5 and the minimum PHP version is 7.4. +#### 💻 Developer Updates +* Added the `gk/block-mcp/post/notices` filter: notes returned as `notices` on `get_page_blocks`, `get_post_info` and `resolve_url`. +* Added the `gk/block-mcp/post/pre-write` filter: return a `WP_Error` to refuse a block edit, `update_post` or Yoast SEO write to a post. A callback that throws refuses the write. + = 2.2.1 on August 20, 2026 = This release stops a damaged install from breaking the WordPress admin, fixes the Claude Desktop installer download being corrupted by output from other plugins, and corrects code block fonts and empty lists written by the assistant. diff --git a/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php b/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php index 8df671b4..add9d16b 100644 --- a/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php +++ b/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php @@ -167,6 +167,39 @@ public function test_edit_block_tree_remove_persists() { $this->assertStringContainsString( '

Keep

', $blocks[0]['innerHTML'] ); } + /** + * A pre-write refusal holds on the Abilities API path too. + * + * Abilities call the controller without the REST server, so a check wired + * only into REST dispatch would let an agent on the MCP Adapter write a + * post another plugin protects. The agent gets the plugin's message and + * the post is unchanged. + */ + public function test_pre_write_refusal_holds_through_abilities() { + $post_id = $this->make_block_post( array( $this->paragraph( '

Live text

' ) ) ); + add_filter( + 'gk/block-mcp/post/pre-write', + static function ( $result, $id ) use ( $post_id ) { + return $id === $post_id ? new \WP_Error( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ) : $result; + }, + 10, + 2 + ); + + $result = wp_get_ability( 'gk-block-mcp/update-blocks' )->execute( + array( + 'post_id' => $post_id, + 'updates' => array( + array( 'flat_index' => 0, 'innerHTML' => '

Agent text

' ), + ), + ) + ); + + $this->assertWPError( $result ); + $this->assertStringContainsString( 'Edit the staged copy #42 instead.', $result->get_error_message() ); + $this->assertStringContainsString( 'Live text', $this->block_tree( $post_id )[0]['innerHTML'] ); + } + /** * update-post changes post fields (title) without touching block content. */ diff --git a/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php b/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php index 3d13e202..895fc1a1 100644 --- a/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php +++ b/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php @@ -557,4 +557,26 @@ public function test_bulk_endpoint_rejects_oversized_batch() { wp_set_current_user( 0 ); } + + // ── pre-write ────────────────────────────────────────────────── + + /** + * SEO writes go through the pre-write check, so a plugin that protects a + * post also keeps an agent from changing its search title or description. + */ + public function test_write_is_refused_when_pre_write_refuses() { + add_filter( + 'gk/block-mcp/post/pre-write', + static function ( $result, $id, $operation ) { + return 'seo' === $operation ? new \WP_Error( 'protected', 'Protected.' ) : $result; + }, + 10, + 3 + ); + + $result = $this->bridge->write_fields_public( $this->post_id, array( 'title' => 'Agent SEO title' ) ); + + $this->assertWPError( $result ); + $this->assertSame( '', get_post_meta( $this->post_id, '_yoast_wpseo_title', true ) ); + } } diff --git a/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php b/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php new file mode 100644 index 00000000..96c4622e --- /dev/null +++ b/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php @@ -0,0 +1,282 @@ + Calls the pre-write filter saw. */ + private $write_calls = array(); + + public function set_up(): void { + parent::set_up(); + $this->editor_id = self::factory()->user->create( array( 'role' => 'editor' ) ); + wp_set_current_user( $this->editor_id ); + $this->write_calls = array(); + } + + // ── fixture helpers ────────────────────────────────────────────────── + + /** + * A paragraph block with a stable ref. + * + * @param string $text Paragraph text. + * @param string $ref gk_ref value. + * + * @return array + */ + private function paragraph( string $text, string $ref = 'blk_aaaa1111' ): array { + $html = '

' . $text . '

'; + + return array( + 'blockName' => 'core/paragraph', + 'attrs' => array( 'metadata' => array( 'gk_ref' => $ref ) ), + 'innerHTML' => $html, + 'innerContent' => array( $html ), + 'innerBlocks' => array(), + ); + } + + /** + * Dispatch a request through the REST server. + * + * @param string $method HTTP method. + * @param string $route Route under the plugin namespace. + * @param array $params Parameters. + * + * @return \WP_REST_Response + */ + private function dispatch( string $method, string $route, array $params = array() ): \WP_REST_Response { + $request = new \WP_REST_Request( $method, '/gk-block-api/v1' . $route ); + foreach ( $params as $key => $value ) { + $request->set_param( $key, $value ); + } + + return rest_get_server()->dispatch( $request ); + } + + /** + * Add a notice for one post. + * + * @param int $post_id Post to annotate. + * @param string $text Notice text. + * + * @return void + */ + private function notice_for( int $post_id, string $text ): void { + add_filter( + 'gk/block-mcp/post/notices', + static function ( $notices, $id ) use ( $post_id, $text ) { + if ( $id === $post_id ) { + $notices[] = $text; + } + return $notices; + }, + 10, + 2 + ); + } + + /** + * Refuse every write to one post, recording each check. + * + * @param int $post_id Post to protect. + * + * @return void + */ + private function refuse_writes_to( int $post_id ): void { + add_filter( + 'gk/block-mcp/post/pre-write', + function ( $result, $id, $operation ) use ( $post_id ) { + $this->write_calls[] = array( $id, $operation ); + if ( $id === $post_id ) { + return new \WP_Error( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ); + } + return $result; + }, + 10, + 3 + ); + } + + // ── notices ────────────────────────────────────────────────────────── + + /** + * Every read an agent starts from carries the post's notices. + * + * Agents resolve a URL or read blocks before editing, so a notice must be + * on each of those responses, including the cheap summary-only read. + */ + public function test_notices_appear_on_every_read_route() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); + $this->notice_for( $post_id, 'Edit the staged copy #42 instead.' ); + + $responses = array( + 'blocks' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id ) ), + 'summary_only' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id, 'summary_only' => true ) ), + 'post_info' => $this->dispatch( 'GET', '/post-info', array( 'post_id' => $post_id ) ), + 'resolve_url' => $this->dispatch( 'GET', '/resolve', array( 'url' => get_permalink( $post_id ) ) ), + ); + + foreach ( $responses as $route => $response ) { + $this->assertSame( 200, $response->get_status(), $route ); + $this->assertSame( array( 'Edit the staged copy #42 instead.' ), $response->get_data()['notices'], $route ); + } + } + + /** + * A post nobody annotates reads as before, with an empty list. + */ + public function test_notices_are_empty_without_a_filter() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); + + $response = $this->dispatch( 'GET', '/post-info', array( 'post_id' => $post_id ) ); + + $this->assertSame( array(), $response->get_data()['notices'] ); + } + + /** + * Notices reach the agent as plain text: markup is stripped, non-strings + * and blanks are dropped, and duplicates from two filters appear once. + */ + public function test_notices_are_sanitized_to_unique_plain_text() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); + add_filter( + 'gk/block-mcp/post/notices', + static function () { + return array( 'Edit #42 instead.', 'Edit #42 instead.', array( 'nested' ), '', ' ' ); + } + ); + + $response = $this->dispatch( 'GET', '/post-info', array( 'post_id' => $post_id ) ); + + $this->assertSame( array( 'Edit #42 instead.' ), $response->get_data()['notices'] ); + } + + /** + * A notices filter that throws must not break the read: the agent still + * gets the post, just without notices. + */ + public function test_notices_filter_that_throws_does_not_break_the_read() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); + add_filter( + 'gk/block-mcp/post/notices', + static function () { + throw new \RuntimeException( 'broken extension' ); + } + ); + + $response = $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id ) ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertSame( array(), $response->get_data()['notices'] ); + } + + // ── pre-write ──────────────────────────────────────────────────────── + + /** + * A refused block edit returns the plugin's message with HTTP 409 and + * leaves the post as it was. + */ + public function test_pre_write_refusal_stops_a_block_edit() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Live text' ) ) ); + $this->refuse_writes_to( $post_id ); + + $response = $this->dispatch( + 'PATCH', + '/posts/' . $post_id . '/blocks/by-ref/blk_aaaa1111', + array( 'id' => $post_id, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Agent text

' ) + ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( 'Edit the staged copy #42 instead.', $response->get_data()['message'] ); + $this->assertStringContainsString( 'Live text', get_post_field( 'post_content', $post_id ) ); + $this->assertSame( array( array( $post_id, 'blocks' ) ), $this->write_calls ); + } + + /** + * update_post is checked too, so an agent cannot change the title or + * status of a protected post. + */ + public function test_pre_write_refusal_stops_update_post() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ), array( 'post_title' => 'Original' ) ); + $this->refuse_writes_to( $post_id ); + + $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'id' => $post_id, 'title' => 'Changed' ) ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( 'Original', get_post_field( 'post_title', $post_id ) ); + $this->assertSame( array( array( $post_id, 'post' ) ), $this->write_calls ); + } + + /** + * Writes to other posts are untouched by a refusal aimed at one post. + */ + public function test_pre_write_allows_posts_it_does_not_refuse() { + $protected = $this->make_block_post( array( $this->paragraph( 'Protected' ) ) ); + $open = $this->make_block_post( array( $this->paragraph( 'Open' ) ) ); + $this->refuse_writes_to( $protected ); + + $response = $this->dispatch( + 'PATCH', + '/posts/' . $open . '/blocks/by-ref/blk_aaaa1111', + array( 'id' => $open, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Edited

' ) + ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertStringContainsString( 'Edited', get_post_field( 'post_content', $open ) ); + } + + /** + * A refusal that sets its own HTTP status keeps it. + */ + public function test_pre_write_refusal_keeps_its_own_status() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); + add_filter( + 'gk/block-mcp/post/pre-write', + static function () { + return new \WP_Error( 'locked', 'Locked.', array( 'status' => 423 ) ); + } + ); + + $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'id' => $post_id, 'title' => 'X' ) ); + + $this->assertSame( 423, $response->get_status() ); + } + + /** + * A pre-write filter that throws fails closed: the write is not made and + * the agent is told why, instead of the guard being silently skipped. + */ + public function test_pre_write_filter_that_throws_fails_closed() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Live text' ) ) ); + add_filter( + 'gk/block-mcp/post/pre-write', + static function () { + throw new \RuntimeException( 'broken guard' ); + } + ); + + $response = $this->dispatch( + 'PATCH', + '/posts/' . $post_id . '/blocks/by-ref/blk_aaaa1111', + array( 'id' => $post_id, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Agent text

' ) + ); + + $this->assertSame( 500, $response->get_status() ); + $this->assertSame( 'write_check_failed', $response->get_data()['code'] ); + $this->assertStringContainsString( 'Live text', get_post_field( 'post_content', $post_id ) ); + } +} From b8275e1fed5a4a7f1b9f2d51a732933e9ff927a8 Mon Sep 17 00:00:00 2001 From: Mwale Kalenga Date: Wed, 14 Oct 2026 15:10:43 +1100 Subject: [PATCH 2/3] Regenerate the tools manifest and server bundle for post notices --- .../tools/read/get_page_blocks.test.ts | 4 ++-- .../gk-block-mcp/assets/mcp-server/index.cjs | 17 ++++++++++++----- .../includes/abilities/tools.manifest.json | 12 +++++++++--- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/__tests__/tools/read/get_page_blocks.test.ts b/src/__tests__/tools/read/get_page_blocks.test.ts index 6f4fe222..0c7ce393 100644 --- a/src/__tests__/tools/read/get_page_blocks.test.ts +++ b/src/__tests__/tools/read/get_page_blocks.test.ts @@ -134,13 +134,13 @@ describe('get_page_blocks — summary_only short-circuit', () => { client.getPageBlocks.mockResolvedValue(pageBlocksResponse); }); - it('returns only post_id + summary when summary_only:true', async () => { + it('returns only post_id, summary and notices when summary_only:true', async () => { const result = await handleReadTool( 'get_page_blocks', { post_id: 1, summary_only: true }, client as any ) as Record; - expect(Object.keys(result).sort()).toEqual(['post_id', 'summary']); + expect(Object.keys(result).sort()).toEqual(['notices', 'post_id', 'summary']); expect(result.post_id).toBe(1); expect(result.summary).toBeDefined(); }); diff --git a/wordpress-plugin/gk-block-mcp/assets/mcp-server/index.cjs b/wordpress-plugin/gk-block-mcp/assets/mcp-server/index.cjs index da72b4b9..5b3c0151 100755 --- a/wordpress-plugin/gk-block-mcp/assets/mcp-server/index.cjs +++ b/wordpress-plugin/gk-block-mcp/assets/mcp-server/index.cjs @@ -41285,7 +41285,7 @@ var DISCOVERY_TOOLS = [ }, { name: "resolve_url", - description: "URL or path \u2192 post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL.", + description: "URL or path \u2192 post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL. Read the returned `notices` before editing.", annotations: { ...READ_ANNOT, title: "Resolve URL to post" }, inputSchema: { type: "object", @@ -41312,7 +41312,7 @@ var DISCOVERY_TOOLS = [ }, { name: "get_post_info", - description: "Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count}`. Replaces wp eval / get_permalink() shell-outs.", + description: "Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count, notices}`. Read `notices` before editing. Replaces wp eval / get_permalink() shell-outs.", annotations: { ...READ_ANNOT, title: "Get post info" }, inputSchema: { type: "object", @@ -41428,7 +41428,7 @@ async function handleDiscoveryTool(toolName, args, client) { var READ_TOOLS = [ { name: "get_page_blocks", - description: 'Get a post\'s blocks. Pass post_id OR url (server resolves URL \u2014 don\'t shell out). Returns `{post_id, summary, blocks[], block_count, warnings}`. Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode ("static"|"dynamic"|"dual"), preference? (when non-preferred)}`. Refs survive sibling shifts \u2014 pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.', + description: 'Get a post\'s blocks. Pass post_id OR url (server resolves URL \u2014 don\'t shell out). Returns `{post_id, summary, blocks[], block_count, warnings, notices}`. Read `notices` before editing: site plugins use them for facts like "edit the staged copy #123 instead". Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode ("static"|"dynamic"|"dual"), preference? (when non-preferred)}`. Refs survive sibling shifts \u2014 pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.', annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true, title: "Get post blocks" }, outputSchema: { type: "object", @@ -41437,7 +41437,8 @@ var READ_TOOLS = [ summary: { type: "object" }, blocks: { type: "array" }, block_count: { type: "number" }, - warnings: { type: "array" } + warnings: { type: "array" }, + notices: { type: "array", items: { type: "string" } } } }, inputSchema: { @@ -41569,7 +41570,8 @@ async function handleReadTool(toolName, args, client) { if (summaryOnly) { return { post_id: postId, - summary: response.summary + summary: response.summary, + notices: response.notices ?? [] }; } const enriched = enrichBlockList(response.blocks || []); @@ -41580,6 +41582,7 @@ async function handleReadTool(toolName, args, client) { blocks: enriched.blocks, block_count: enriched.blocks.length, warnings: enriched.warnings, + notices: response.notices ?? [], ...pagination !== void 0 ? { pagination } : {} }; } @@ -53906,6 +53909,10 @@ The MCP does this for you: If the user says "change X on https://example.com/some-page/", your first tool call should be \`get_page_blocks({ url: "...", search: "keyword" })\` or \`resolve_url({ url: "..." })\` \u2014 not a shell command. +## Notices: read them before editing + +\`get_page_blocks\`, \`get_post_info\` and \`resolve_url\` return \`notices\`: notes from this site's plugins about the post. A URL always resolves to the published page, so a notice may tell you the change belongs somewhere else, such as "a staged copy of this page is waiting; edit #123 instead". Follow it. A write a plugin refuses comes back as an error that says what to do instead. + ## Moving / reordering blocks NEVER do a move as separate \`insert_blocks\` + \`delete_block\` calls \u2014 if the delete is skipped or fails, the page ends up with an orphaned clone of the original. The atomic primitive is the \`move\` op on \`edit_block_tree\`: diff --git a/wordpress-plugin/gk-block-mcp/includes/abilities/tools.manifest.json b/wordpress-plugin/gk-block-mcp/includes/abilities/tools.manifest.json index 3e05710e..7579b7e9 100644 --- a/wordpress-plugin/gk-block-mcp/includes/abilities/tools.manifest.json +++ b/wordpress-plugin/gk-block-mcp/includes/abilities/tools.manifest.json @@ -240,7 +240,7 @@ "name": "resolve_url", "ability": "gk-block-mcp/resolve-url", "label": "Resolve URL to post", - "description": "URL or path → post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL.", + "description": "URL or path → post ID. Accepts full URLs or site-relative paths. Run this before get_page_blocks / update_block / edit_block_tree when you only have a URL. Read the returned `notices` before editing.", "input_schema": { "type": "object", "properties": { @@ -307,7 +307,7 @@ "name": "get_post_info", "ability": "gk-block-mcp/get-post-info", "label": "Get post info", - "description": "Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count}`. Replaces wp eval / get_permalink() shell-outs.", + "description": "Post metadata by post_id, url, or slug+post_type. Returns `{post_id, title, status, post_url, edit_url, modified, created, parent_id, author, mime_type, comment_count, notices}`. Read `notices` before editing. Replaces wp eval / get_permalink() shell-outs.", "input_schema": { "type": "object", "properties": { @@ -343,7 +343,7 @@ "name": "get_page_blocks", "ability": "gk-block-mcp/get-page-blocks", "label": "Get post blocks", - "description": "Get a post's blocks. Pass post_id OR url (server resolves URL — don't shell out). Returns `{post_id, summary, blocks[], block_count, warnings}`. Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode (\"static\"|\"dynamic\"|\"dual\"), preference? (when non-preferred)}`. Refs survive sibling shifts — pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.", + "description": "Get a post's blocks. Pass post_id OR url (server resolves URL — don't shell out). Returns `{post_id, summary, blocks[], block_count, warnings, notices}`. Read `notices` before editing: site plugins use them for facts like \"edit the staged copy #123 instead\". Each block: `{index (flat), top_level_counter? (top-level only), path, ref (stable gk_ref), name, attributes, innerHTML?, dynamic, storage_mode (\"static\"|\"dynamic\"|\"dual\"), preference? (when non-preferred)}`. Refs survive sibling shifts — pass them to update_block / delete_block / edit_block_tree to chain mutations without re-fetching. Use outline:true or summary_only:true for cheap inspection.", "input_schema": { "type": "object", "properties": { @@ -414,6 +414,12 @@ }, "warnings": { "type": "array" + }, + "notices": { + "type": "array", + "items": { + "type": "string" + } } } }, From d0fd9d9a5100a3d7086f43509cc0eebf23f2c8ba Mon Sep 17 00:00:00 2001 From: Mwale Kalenga Date: Wed, 14 Oct 2026 15:39:30 +1100 Subject: [PATCH 3/3] Keep pre-write refusals from being undone and skip saving refs to refused posts --- .../includes/class-block-reader.php | 6 + .../includes/class-post-extensions.php | 33 ++--- .../includes/class-yoast-bridge.php | 2 +- wordpress-plugin/gk-block-mcp/readme.txt | 2 +- .../tests/Abilities/AbilityExecutionTest.php | 8 +- .../tests/Integrations/YoastBridgeTest.php | 8 +- .../tests/REST/PostExtensionsTest.php | 115 +++++++++++++++--- 7 files changed, 132 insertions(+), 42 deletions(-) diff --git a/wordpress-plugin/gk-block-mcp/includes/class-block-reader.php b/wordpress-plugin/gk-block-mcp/includes/class-block-reader.php index c9985735..b32c4973 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-block-reader.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-block-reader.php @@ -240,7 +240,13 @@ public function get_blocks( $post_id, $render = false, $persist_refs = true ) { // silently (no revision) so the refs survive across reads/writes. // When false, refs are still surfaced in-memory via the cache reference above // so a second read in the same request sees the same ephemeral refs. + // Saving refs changes post_content, so it obeys the same pre-write + // check as an edit. When a plugin refuses, the read still works with + // in-memory refs and the post is left as it is. $dirty = $this->crud->assign_missing_refs_recursive( $blocks ); + if ( $dirty && $persist_refs && true !== Post_Extensions::check_write( $post_id, 'blocks' ) ) { + $persist_refs = false; + } if ( $dirty && $persist_refs ) { // Concurrency guard. Two readers landing on a fresh post could both // generate random refs and both call persist_ref_assignments(); the diff --git a/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php b/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php index 7261b643..bede255f 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-post-extensions.php @@ -85,7 +85,7 @@ public static function notices( $post_id, $context ) { /** * Ask other plugins whether an agent may write to a post. * - * Runs after the capability check, before anything is written. A filter + * Runs after the capability check, before anything is written. A callback * that throws is treated as a refusal, so a broken guard fails closed. * * @since 2.3.0 @@ -98,30 +98,33 @@ public static function notices( $post_id, $context ) { * @return true|\WP_Error True to allow, or the refusal to return to the agent. */ public static function check_write( $post_id, $operation ) { + $refusals = new \WP_Error(); + try { /** * Stop an agent's write to a post before it happens. * - * Return a WP_Error to refuse the write; its message is what the - * agent sees, so say what to do instead. Without a status in the - * error data, the response is HTTP 409. Return null to allow. + * Add an error to `$refusals` to refuse the write; its message is + * what the agent sees, so say what to do instead. Without a status + * in the error data, the response is HTTP 409. Every callback gets + * the same object, so a later callback cannot undo an earlier + * refusal by returning a different value. * * @since 2.3.0 * * @example * // Keep agents off pages that are frozen for review. - * add_filter( 'gk/block-mcp/post/pre-write', function ( $result, $post_id ) { + * add_action( 'gk/block-mcp/post/pre-write', function ( $refusals, $post_id ) { * if ( get_post_meta( $post_id, 'frozen_for_review', true ) ) { - * return new WP_Error( 'frozen', 'This page is frozen for legal review. Do not edit it.' ); + * $refusals->add( 'frozen', 'This page is frozen for legal review. Do not edit it.' ); * } - * return $result; * }, 10, 2 ); * - * @param null|\WP_Error $result Null to allow, or a refusal. - * @param int $post_id Post about to be written. - * @param string $operation `blocks`, `post` or `seo`. + * @param \WP_Error $refusals Add an error to refuse the write. + * @param int $post_id Post about to be written. + * @param string $operation `blocks`, `post` or `seo`. */ - $result = apply_filters( 'gk/block-mcp/post/pre-write', null, (int) $post_id, (string) $operation ); + do_action( 'gk/block-mcp/post/pre-write', $refusals, (int) $post_id, (string) $operation ); } catch ( \Throwable $e ) { self::log( 'gk/block-mcp/post/pre-write', $e ); @@ -132,16 +135,16 @@ public static function check_write( $post_id, $operation ) { ); } - if ( ! is_wp_error( $result ) ) { + if ( ! $refusals->has_errors() ) { return true; } - $data = $result->get_error_data(); + $data = $refusals->get_error_data(); if ( ! is_array( $data ) || ! isset( $data['status'] ) ) { - $result->add_data( array_merge( is_array( $data ) ? $data : array(), array( 'status' => 409 ) ) ); + $refusals->add_data( array_merge( is_array( $data ) ? $data : array(), array( 'status' => 409 ) ) ); } - return $result; + return $refusals; } /** diff --git a/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php b/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php index 6de4ab22..81b36beb 100644 --- a/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php +++ b/wordpress-plugin/gk-block-mcp/includes/class-yoast-bridge.php @@ -309,7 +309,7 @@ protected function read_fields( $post_id ) { * @return true|\WP_Error */ protected function write_fields( $post_id, array $fields ) { - $post_id = (int) $post_id; + $post_id = absint( $post_id ); $write_check = Post_Extensions::check_write( $post_id, 'seo' ); if ( is_wp_error( $write_check ) ) { return $write_check; diff --git a/wordpress-plugin/gk-block-mcp/readme.txt b/wordpress-plugin/gk-block-mcp/readme.txt index c73fd3da..bc46ff9c 100644 --- a/wordpress-plugin/gk-block-mcp/readme.txt +++ b/wordpress-plugin/gk-block-mcp/readme.txt @@ -130,7 +130,7 @@ Visit Settings → Block MCP. Set the score for a namespace to less than 10 to m #### 💻 Developer Updates * Added the `gk/block-mcp/post/notices` filter: notes returned as `notices` on `get_page_blocks`, `get_post_info` and `resolve_url`. -* Added the `gk/block-mcp/post/pre-write` filter: return a `WP_Error` to refuse a block edit, `update_post` or Yoast SEO write to a post. A callback that throws refuses the write. +* Added the `gk/block-mcp/post/pre-write` action: add an error to the `WP_Error` it passes to refuse a block edit, `update_post` or Yoast SEO write to a post. A later callback cannot undo an earlier refusal, and a callback that throws refuses the write. Saving block refs during a read is skipped while writes to the post are refused. = 2.2.1 on August 20, 2026 = diff --git a/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php b/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php index add9d16b..6119c6ab 100644 --- a/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php +++ b/wordpress-plugin/gk-block-mcp/tests/Abilities/AbilityExecutionTest.php @@ -177,10 +177,12 @@ public function test_edit_block_tree_remove_persists() { */ public function test_pre_write_refusal_holds_through_abilities() { $post_id = $this->make_block_post( array( $this->paragraph( '

Live text

' ) ) ); - add_filter( + add_action( 'gk/block-mcp/post/pre-write', - static function ( $result, $id ) use ( $post_id ) { - return $id === $post_id ? new \WP_Error( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ) : $result; + static function ( $refusals, $id ) use ( $post_id ) { + if ( $id === $post_id ) { + $refusals->add( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ); + } }, 10, 2 diff --git a/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php b/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php index 895fc1a1..e83217c3 100644 --- a/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php +++ b/wordpress-plugin/gk-block-mcp/tests/Integrations/YoastBridgeTest.php @@ -565,10 +565,12 @@ public function test_bulk_endpoint_rejects_oversized_batch() { * post also keeps an agent from changing its search title or description. */ public function test_write_is_refused_when_pre_write_refuses() { - add_filter( + add_action( 'gk/block-mcp/post/pre-write', - static function ( $result, $id, $operation ) { - return 'seo' === $operation ? new \WP_Error( 'protected', 'Protected.' ) : $result; + static function ( $refusals, $id, $operation ) { + if ( 'seo' === $operation ) { + $refusals->add( 'protected', 'Protected.' ); + } }, 10, 3 diff --git a/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php b/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php index 96c4622e..2233a908 100644 --- a/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php +++ b/wordpress-plugin/gk-block-mcp/tests/REST/PostExtensionsTest.php @@ -17,7 +17,7 @@ class PostExtensionsTest extends RestControllerTestCase { /** @var int Editor — holds edit_post on the fixture posts. */ private $editor_id; - /** @var array Calls the pre-write filter saw. */ + /** @var array Calls the pre-write action saw. */ private $write_calls = array(); public function set_up(): void { @@ -50,7 +50,9 @@ private function paragraph( string $text, string $ref = 'blk_aaaa1111' ): array } /** - * Dispatch a request through the REST server. + * Dispatch a request through the REST server. The server fills the URL + * parameters (`id`, `ref`) from the matched route, so `$params` holds + * only body and query arguments. * * @param string $method HTTP method. * @param string $route Route under the plugin namespace. @@ -97,14 +99,13 @@ static function ( $notices, $id ) use ( $post_id, $text ) { * @return void */ private function refuse_writes_to( int $post_id ): void { - add_filter( + add_action( 'gk/block-mcp/post/pre-write', - function ( $result, $id, $operation ) use ( $post_id ) { + function ( $refusals, $id, $operation ) use ( $post_id ) { $this->write_calls[] = array( $id, $operation ); if ( $id === $post_id ) { - return new \WP_Error( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ); + $refusals->add( 'staged_copy_waiting', 'Edit the staged copy #42 instead.' ); } - return $result; }, 10, 3 @@ -124,8 +125,8 @@ public function test_notices_appear_on_every_read_route() { $this->notice_for( $post_id, 'Edit the staged copy #42 instead.' ); $responses = array( - 'blocks' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id ) ), - 'summary_only' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id, 'summary_only' => true ) ), + 'blocks' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks' ), + 'summary_only' => $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'summary_only' => true ) ), 'post_info' => $this->dispatch( 'GET', '/post-info', array( 'post_id' => $post_id ) ), 'resolve_url' => $this->dispatch( 'GET', '/resolve', array( 'url' => get_permalink( $post_id ) ) ), ); @@ -178,7 +179,7 @@ static function () { } ); - $response = $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks', array( 'id' => $post_id ) ); + $response = $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks' ); $this->assertSame( 200, $response->get_status() ); $this->assertSame( array(), $response->get_data()['notices'] ); @@ -197,7 +198,7 @@ public function test_pre_write_refusal_stops_a_block_edit() { $response = $this->dispatch( 'PATCH', '/posts/' . $post_id . '/blocks/by-ref/blk_aaaa1111', - array( 'id' => $post_id, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Agent text

' ) + array( 'innerHTML' => '

Agent text

' ) ); $this->assertSame( 409, $response->get_status() ); @@ -214,7 +215,7 @@ public function test_pre_write_refusal_stops_update_post() { $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ), array( 'post_title' => 'Original' ) ); $this->refuse_writes_to( $post_id ); - $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'id' => $post_id, 'title' => 'Changed' ) ); + $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'title' => 'Changed' ) ); $this->assertSame( 409, $response->get_status() ); $this->assertSame( 'Original', get_post_field( 'post_title', $post_id ) ); @@ -232,7 +233,7 @@ public function test_pre_write_allows_posts_it_does_not_refuse() { $response = $this->dispatch( 'PATCH', '/posts/' . $open . '/blocks/by-ref/blk_aaaa1111', - array( 'id' => $open, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Edited

' ) + array( 'innerHTML' => '

Edited

' ) ); $this->assertSame( 200, $response->get_status() ); @@ -244,25 +245,25 @@ public function test_pre_write_allows_posts_it_does_not_refuse() { */ public function test_pre_write_refusal_keeps_its_own_status() { $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ) ); - add_filter( + add_action( 'gk/block-mcp/post/pre-write', - static function () { - return new \WP_Error( 'locked', 'Locked.', array( 'status' => 423 ) ); + static function ( $refusals ) { + $refusals->add( 'locked', 'Locked.', array( 'status' => 423 ) ); } ); - $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'id' => $post_id, 'title' => 'X' ) ); + $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'title' => 'X' ) ); $this->assertSame( 423, $response->get_status() ); } /** - * A pre-write filter that throws fails closed: the write is not made and + * A pre-write callback that throws fails closed: the write is not made and * the agent is told why, instead of the guard being silently skipped. */ public function test_pre_write_filter_that_throws_fails_closed() { $post_id = $this->make_block_post( array( $this->paragraph( 'Live text' ) ) ); - add_filter( + add_action( 'gk/block-mcp/post/pre-write', static function () { throw new \RuntimeException( 'broken guard' ); @@ -272,11 +273,87 @@ static function () { $response = $this->dispatch( 'PATCH', '/posts/' . $post_id . '/blocks/by-ref/blk_aaaa1111', - array( 'id' => $post_id, 'ref' => 'blk_aaaa1111', 'innerHTML' => '

Agent text

' ) + array( 'innerHTML' => '

Agent text

' ) ); $this->assertSame( 500, $response->get_status() ); $this->assertSame( 'write_check_failed', $response->get_data()['code'] ); $this->assertStringContainsString( 'Live text', get_post_field( 'post_content', $post_id ) ); } + + /** + * A later callback cannot undo an earlier refusal. With a filter, a + * callback that returned null would have erased it and let the write + * through. + */ + public function test_pre_write_refusal_cannot_be_undone_by_a_later_callback() { + $post_id = $this->make_block_post( array( $this->paragraph( 'Body' ) ), array( 'post_title' => 'Original' ) ); + $this->refuse_writes_to( $post_id ); + add_action( + 'gk/block-mcp/post/pre-write', + static function () { + return null; + }, + 20 + ); + + $response = $this->dispatch( 'PATCH', '/posts/' . $post_id, array( 'title' => 'Changed' ) ); + + $this->assertSame( 409, $response->get_status() ); + $this->assertSame( 'Original', get_post_field( 'post_title', $post_id ) ); + } + + /** + * Reading a post whose blocks have no refs normally saves fresh refs into + * post_content. That is a write, so a refused post is left untouched and + * the read still returns blocks with in-memory refs. + */ + public function test_read_does_not_save_refs_to_a_refused_post() { + $html = '

Refused, no ref yet

'; + $post_id = $this->make_block_post( + array( + array( + 'blockName' => 'core/paragraph', + 'attrs' => array(), + 'innerHTML' => $html, + 'innerContent' => array( $html ), + 'innerBlocks' => array(), + ), + ) + ); + $before = get_post_field( 'post_content', $post_id ); + $this->refuse_writes_to( $post_id ); + + $response = $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks' ); + + $this->assertSame( 200, $response->get_status() ); + $this->assertNotEmpty( $response->get_data()['blocks'][0]['ref'] ); + clean_post_cache( $post_id ); + $this->assertSame( $before, get_post_field( 'post_content', $post_id ) ); + } + + /** + * Without a refusal, a read saves the refs as before. The text differs + * from the refused case: the reader caches parsed blocks by post ID and + * content, and post IDs are reused between tests. + */ + public function test_read_saves_refs_when_writes_are_allowed() { + $html = '

Allowed, no ref yet

'; + $post_id = $this->make_block_post( + array( + array( + 'blockName' => 'core/paragraph', + 'attrs' => array(), + 'innerHTML' => $html, + 'innerContent' => array( $html ), + 'innerBlocks' => array(), + ), + ) + ); + + $this->dispatch( 'GET', '/posts/' . $post_id . '/blocks' ); + + clean_post_cache( $post_id ); + $this->assertStringContainsString( 'gk_ref', get_post_field( 'post_content', $post_id ) ); + } }