feat: content-create and content-update with schema validation

All-or-nothing writes: validation (fields, terms, featured image, parent,
template) before any write; failed extras delete the new draft (create) or
restore revision, old columns, fields, terms and featured image (update).
content-update requires rev; Rev::ofPost covers content, title, excerpt,
status and post_modified_gmt. MetaFieldSource::write() now throws on failure.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
2026-09-25 23:01:48 +02:00
co-authored by Claude Opus 5.5
parent b9d46f3cec
commit 4f9a47fe32
15 changed files with 1355 additions and 9 deletions
@@ -0,0 +1,244 @@
<?php
declare(strict_types=1);
namespace LIT\MCP\Integrations\WordPress\Content;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Abilities\Rev;
use LIT\MCP\Abilities\ToolResult;
use LIT\MCP\ChangeLog\ChangeLog;
use LIT\MCP\Integrations\WordPress\PostGuard;
use LIT\MCP\Integrations\WordPress\RevisionPoint;
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
use RuntimeException;
use Throwable;
use WP_Error;
use WP_Post;
/**
* lit/content-update: changes an entry without touching its status. rev (from
* lit/content-get) is required so parallel edits are never overwritten (spec §2
* principle 7). All or nothing (spec §8.2): input is validated first; if fields,
* terms or the featured image fail after the post row was updated, the row is
* restored from the restore-point revision (plus old values for columns revisions
* do not cover), the extras get their old values back, and the error is rethrown
* (the AbilityRegistrar logs it and reports lit_internal_error).
*/
final class ContentUpdateAbility implements Ability
{
private const CHANGE_KEYS = [
'title', 'content', 'excerpt', 'slug', 'parent', 'menu_order', 'template', 'terms', 'fields', 'featured_image',
];
/** Post columns a revision stores (and wp_restore_post_revision() restores). */
private const REVISIONED = ['post_title', 'post_content', 'post_excerpt'];
public function __construct(
private ContentSchema $schema,
private PostWriter $writer,
private ChangeLog $log
) {
}
public function name(): string
{
return 'lit/content-update';
}
public function label(): string
{
return 'Inhalt ändern';
}
public function description(): string
{
return 'Ändert Kerndaten, Begriffe, Felder oder Beitragsbild eines Eintrags; der Status bleibt '
. 'unverändert (veröffentlichte Inhalte werden live geändert, vorher entsteht eine Revision). '
. 'rev aus lit-content-get ist Pflicht, damit parallele Änderungen nicht überschrieben werden; '
. 'die Antwort enthält die neue rev für weitere Änderungen. '
. 'content von Divi-Seiten ist hier nicht änderbar.';
}
public function inputSchema(): array
{
return [
'type' => 'object',
'properties' => array_merge([
'post_id' => ['type' => 'integer', 'minimum' => 1],
'rev' => ['type' => 'string', 'description' => 'rev aus lit-content-get (optimistische Sperre).'],
'title' => ['type' => 'string', 'minLength' => 1],
], PostWriter::inputProperties()),
'required' => ['post_id', 'rev'],
'additionalProperties' => false,
];
}
public function outputSchema(): ?array
{
return ToolResult::schema();
}
public function annotations(): array
{
return ['readonly' => false, 'destructive' => false, 'idempotent' => true];
}
public function isDirect(): bool
{
return true;
}
public function permission(array $input): bool|WP_Error
{
$post = PostGuard::editable($input['post_id'] ?? null, $this->schema);
return $post instanceof WP_Error ? $post : true;
}
public function execute(array $input): mixed
{
$post = PostGuard::editable($input['post_id'] ?? null, $this->schema);
if ($post instanceof WP_Error) {
return $post;
}
if (! isset($input['rev']) || $input['rev'] !== Rev::ofPost($post)) {
return Errors::revMismatch();
}
if (array_key_exists('content', $input) && PostPresenter::usesDivi($post)) {
return Errors::unsupported(
'Divi-Inhalte können nicht als Rohtext überschrieben werden; nichts wurde gespeichert.',
'Divi-Struktur über lit-divi-outline und die lit-divi-*-Tools bearbeiten; Titel, Auszug, '
. 'Felder und Begriffe hier ohne content ändern.'
);
}
$data = $this->writer->postData($input);
if ($data === [] && ! $this->writer->hasExtras($input)) {
return Errors::invalidInput(
'Nichts zu ändern.',
[],
'Mindestens eines angeben: ' . implode(', ', self::CHANGE_KEYS) . '.'
);
}
$postType = (string) $post->post_type;
$prepared = $this->writer->prepare($postType, $input, false);
if ($prepared instanceof WP_Error) {
return $prepared;
}
$postId = (int) $post->ID;
$snapshot = $this->writer->snapshot($postId, $postType, $prepared, $input);
$revisionId = RevisionPoint::capture($postId);
$rowUpdated = false;
try {
if ($data !== []) {
$result = wp_update_post(wp_slash(array_merge($data, ['ID' => $postId])), true);
if ($result instanceof WP_Error) {
return Errors::invalidInput(
'WordPress hat die Änderung abgelehnt: ' . $result->get_error_message()
);
}
$rowUpdated = true;
}
$this->writer->writeExtras($postId, $postType, $prepared, $input);
} catch (Throwable $e) {
$this->rollBack($post, $rowUpdated ? $data : [], $revisionId, $snapshot, $e);
}
do_action('lit_mcp_after_save', $postId, $this->name(), $input);
$updated = get_post($postId);
$updated = $updated instanceof WP_Post ? $updated : $post;
$changedKeys = array_keys(array_intersect_key($input, array_flip(self::CHANGE_KEYS)));
$summary = sprintf('"%s" geändert: %s', $updated->post_title, implode(', ', $changedKeys));
$logId = $this->log->record($this->name(), $postType, (string) $postId, $summary, $revisionId);
return ToolResult::ok(sprintf('%s (Status unverändert: %s).', $summary, $updated->post_status))
->changed((string) $postId, $postType, 'updated', (string) $updated->post_title)
->rev(Rev::ofPost($updated))
->revisionId($revisionId)
->logId($logId)
->urls((string) get_preview_post_link($updated), (string) get_edit_post_link($postId, 'raw'))
->warnings($prepared['warnings'])
->toArray();
}
/**
* @param array<string, mixed> $data Columns that were written to the post row.
* @param array<string, mixed> $snapshot Output of PostWriter::snapshot().
* @throws RuntimeException Always – the original failure plus the rollback outcome.
*/
private function rollBack(WP_Post $post, array $data, ?int $revisionId, array $snapshot, Throwable $cause): never
{
$failures = [];
try {
$this->writer->restore((int) $post->ID, (string) $post->post_type, $snapshot);
} catch (Throwable $e) {
$failures[] = $e->getMessage();
}
try {
$this->restoreRow($post, $data, $revisionId);
} catch (Throwable $e) {
$failures[] = $e->getMessage();
}
throw new RuntimeException(
sprintf(
'Update of post %d failed (%s); %s.',
(int) $post->ID,
$cause->getMessage(),
$failures === [] ? 'changes rolled back' : 'rollback incomplete: ' . implode('; ', $failures)
),
0,
$cause
);
}
/**
* Title, content and excerpt come back from the restore-point revision when that
* revision reflects the pre-update state (revisions enabled: RevisionPoint then
* saved or confirmed it). Everything else – and everything when revisions are off,
* where the newest revision may be stale – gets the value read before the update.
*
* @param array<string, mixed> $data
* @throws RuntimeException
*/
private function restoreRow(WP_Post $post, array $data, ?int $revisionId): void
{
if ($data === []) {
return;
}
$old = [];
foreach (array_keys($data) as $column) {
$old[$column] = $column === 'page_template'
? ((string) get_page_template_slug($post) ?: PostWriter::DEFAULT_TEMPLATE)
: $post->{$column};
}
$fromRevision = array_values(array_intersect(array_keys($old), self::REVISIONED));
if ($revisionId !== null && $fromRevision !== [] && wp_revisions_enabled($post)) {
$restored = wp_restore_post_revision($revisionId, $fromRevision);
if ($restored && ! is_wp_error($restored)) {
$old = array_diff_key($old, array_flip($fromRevision));
}
}
if ($old === []) {
return;
}
$result = wp_update_post(wp_slash(array_merge($old, ['ID' => (int) $post->ID])), true);
if ($result instanceof WP_Error || ! $result) {
$message = $result instanceof WP_Error ? $result->get_error_message() : 'unknown error';
throw new RuntimeException('Post row could not be restored: ' . $message);
}
}
}