feat: deferred 1a items - menu_rev lock, lit_mcp_guides filter, warnings, schedule guard precision

Task 14 (rulings P17/P18, Q10):
- lit/menu-get returns menu_rev (Rev::ofMenu over id, parent, position,
  title, url, object, object_id); lit/menu-set-items requires it, refuses
  a stale one with rev_mismatch (hint: lit/menu-get) and returns the new
  menu_rev. Errors::revMismatch takes an optional message/hint.
- GuideRepository: filter lit_mcp_guides adds/overrides topics; invalid
  topic names and non-string content are ignored, files stay the default.
- lit/post-trash names front page, posts page and linking menus in the
  confirmation and as warnings; lit/menu-assign-location needs confirm
  to remove an assigned menu and names it; lit/post-schedule warns that
  a private entry becomes public; Divi hints no longer point to
  non-existing lit-divi-* tools.
- PostGuard::missedSchedule: 60 s publish window, zero GMT date falls
  back to get_gmt_from_date(post_date); post-schedule refuses dates
  within that window.
- write_failed after a clean rollback that keeps a revision/backup says
  "Die Aenderung wurde nicht gespeichert (... bleibt erhalten)" via the
  new state parameter (Errors::writeFailed / WriteFailed rolledBackState).
- wp-basis-smoke: menu_rev flow, unassign confirm, trash/menu and
  private-schedule warnings.

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-26 04:33:15 +02:00
co-authored by Claude Opus 5.5
parent 7035448f7d
commit 251934ce53
32 changed files with 700 additions and 98 deletions
@@ -29,7 +29,7 @@ final class ContentGetAbility implements Ability
{
return 'Liest einen Eintrag vollständig: Kerndaten, Inhalt, Begriffe, alle Felder (Pods/Meta), '
. 'Beitragsbild, rev (für lit-content-update). Bei Divi-Inhalten wird content nicht ausgegeben; '
. 'hints verweist dann auf lit-divi-outline.';
. 'hints erklärt dann, wie sie bearbeitet werden.';
}
public function inputSchema(): array
@@ -121,8 +121,7 @@ final class ContentUpdateAbility implements Ability
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.'
PostPresenter::DIVI_NOTE . ' Titel, Auszug, Felder und Begriffe hier ohne content ändern.'
);
}
@@ -235,7 +234,17 @@ final class ContentUpdateAbility implements Ability
$detail = sprintf('Update of post %d failed: %s', $postId, $cause->getMessage());
if ($failures === []) {
throw new WriteFailed(self::REASON, true, $postId, $revisionId, $cause, $detail);
throw new WriteFailed(
self::REASON,
true,
$postId,
$revisionId,
$cause,
$detail,
rolledBackState: $revisionId === null
? null
: Errors::notSavedKeeping(sprintf('Revision %d', $revisionId))
);
}
$this->log->recordPartial(
@@ -16,10 +16,11 @@ use WP_Post;
*/
class PostPresenter
{
public const DIVI_HINT = 'Dieser Inhalt ist mit Divi gebaut. Die Divi-Struktur wird über lit-divi-outline '
. 'gelesen und mit den lit-divi-*-Tools bearbeitet; fehlen diese Tools, kann der Divi-Inhalt hier nicht '
. 'bearbeitet werden. content wird deshalb nicht ausgegeben; Titel, Auszug, Felder und Begriffe sind '
. 'über lit/content-update (direkt: lit-content-update) änderbar.';
public const DIVI_NOTE = 'Divi-Werkzeuge folgen in einer späteren Version; bis dahin im Divi-Builder bearbeiten.';
public const DIVI_HINT = 'Dieser Inhalt ist mit Divi gebaut; content wird deshalb nicht ausgegeben. '
. self::DIVI_NOTE . ' Titel, Auszug, Felder und Begriffe sind über lit/content-update '
. '(direkt: lit-content-update) änderbar.';
public function __construct(private ContentSchema $schema)
{
@@ -13,8 +13,9 @@ use WP_Error;
/**
* lit/menu-assign-location: assigns a menu to a theme location (menu_id 0 removes
* the assignment). Idempotent: assigning the same menu again, or removing an
* already-empty location, changes nothing but still succeeds.
* the assignment – the menu then disappears from the site, so removing an existing
* assignment needs confirm: true). Idempotent: assigning the same menu again, or
* removing an already-empty location, changes nothing but still succeeds.
*/
final class MenuAssignLocationAbility implements Ability
{
@@ -34,7 +35,8 @@ final class MenuAssignLocationAbility implements Ability
public function description(): string
{
return 'Weist einer Theme-Position (siehe lit/menu-list) ein Menü zu; menu_id 0 entfernt die Zuweisung. '
return 'Weist einer Theme-Position (siehe lit/menu-list) ein Menü zu; menu_id 0 entfernt die Zuweisung '
. '(das Menü verschwindet dann von der Website; nur nach Rückfrage beim Nutzer mit confirm: true). '
. 'Das vorher zugewiesene Menü steht in previous_menu_id.';
}
@@ -45,6 +47,10 @@ final class MenuAssignLocationAbility implements Ability
'properties' => [
'location' => ['type' => 'string', 'minLength' => 1],
'menu_id' => ['type' => 'integer', 'minimum' => 0],
'confirm' => [
'type' => 'boolean',
'description' => 'Nur nötig bei menu_id 0 (Zuweisung entfernen): true nach Bestätigung.',
],
],
'required' => ['location', 'menu_id'],
'additionalProperties' => false,
@@ -90,12 +96,23 @@ final class MenuAssignLocationAbility implements Ability
}
$previous = MenuLocations::assigned()[$location] ?? 0;
$removed = $menuId === 0 && $previous > 0 ? self::menuLabel($previous) : null;
if ($removed !== null && ($input['confirm'] ?? false) !== true) {
return Errors::confirmRequired(sprintf(
'Menü %s von der Position %s entfernen? Es wird dort dann nicht mehr angezeigt.',
$removed,
$location
));
}
MenuLocations::assign($location, $menuId);
$action = $menuId > 0 ? 'assigned' : 'unassigned';
$summary = $menuId > 0
? sprintf('Menü %d der Position %s zugewiesen', $menuId, $location)
: sprintf('Zuweisung der Position %s entfernt', $location);
$summary = match (true) {
$menuId > 0 => sprintf('Menü %d der Position %s zugewiesen', $menuId, $location),
$removed !== null => sprintf('Menü %s von der Position %s entfernt', $removed, $location),
default => sprintf('Zuweisung der Position %s entfernt', $location),
};
// The assignment is saved – a change log failure from here on is logged and reported as a warning only.
$warnings = [];
@@ -113,4 +130,14 @@ final class MenuAssignLocationAbility implements Ability
->with('previous_menu_id', $previous > 0 ? $previous : null)
->toArray();
}
/** '"Hauptmenü" (ID 3)', or just the ID when the menu itself no longer exists. */
private static function menuLabel(int $menuId): string
{
$menu = wp_get_nav_menu_object($menuId);
return is_object($menu)
? sprintf('"%s" (ID %d)', $menu->name, $menuId)
: sprintf('(ID %d)', $menuId);
}
}
@@ -6,6 +6,7 @@ namespace LIT\MCP\Integrations\WordPress\Menus;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Abilities\Rev;
use WP_Error;
/**
@@ -29,7 +30,8 @@ final class MenuGetAbility implements Ability
return 'Liefert ein Menü als Baum (id, title, type post/taxonomy/custom, object/object_id, url, '
. 'children). object_id und url sind bei post/taxonomy-Einträgen nur informativ (WordPress leitet '
. 'sie aus dem verlinkten Objekt ab); nur bei custom-Einträgen ist url maßgeblich. Der Baum kann '
. 'bearbeitet an lit/menu-set-items zurückgegeben werden.';
. 'bearbeitet an lit/menu-set-items zurückgegeben werden, zusammen mit menu_rev (Stand des Menüs, '
. 'damit parallele Änderungen nicht überschrieben werden).';
}
public function inputSchema(): array
@@ -51,8 +53,12 @@ final class MenuGetAbility implements Ability
'name' => ['type' => 'string'],
'locations' => ['type' => 'array', 'items' => ['type' => 'string']],
'items' => ['type' => 'array', 'items' => MenuTree::nodeSchema()],
'menu_rev' => [
'type' => 'string',
'description' => 'Stand des Menüs; Pflicht für lit/menu-set-items.',
],
],
'required' => ['id', 'name', 'locations', 'items'],
'required' => ['id', 'name', 'locations', 'items', 'menu_rev'],
];
}
@@ -82,12 +88,14 @@ final class MenuGetAbility implements Ability
}
$items = wp_get_nav_menu_items($menuId);
$items = is_array($items) ? $items : [];
return [
'id' => (int) $menu->term_id,
'name' => (string) $menu->name,
'locations' => MenuLocations::of((int) $menu->term_id),
'items' => MenuTree::build(is_array($items) ? $items : []),
'items' => MenuTree::build($items),
'menu_rev' => Rev::ofMenu($items),
];
}
}
@@ -7,6 +7,7 @@ namespace LIT\MCP\Integrations\WordPress\Menus;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\Errors;
use LIT\MCP\Abilities\FollowUp;
use LIT\MCP\Abilities\Rev;
use LIT\MCP\Abilities\ToolResult;
use LIT\MCP\Abilities\WriteFailed;
use LIT\MCP\ChangeLog\ChangeLog;
@@ -17,7 +18,9 @@ use WP_Error;
* as add/move/remove operations. Both run through one path: operations are applied to
* the current tree (MenuOperations), the resulting tree is validated as a whole
* (MenuWriter::plan) before anything is written, removals need confirm: true, and the
* answer always carries previous_items so a mistake can be rebuilt. Write failures
* answer always carries previous_items so a mistake can be rebuilt. menu_rev (from
* lit/menu-get, Rev::ofMenu) is the optimistic lock: a menu changed since reading is
* refused with rev_mismatch before anything is planned or written. Write failures
* surface as WriteFailed (lit_write_failed / lit_partial_write) from MenuWriter::apply.
*/
final class MenuSetItemsAbility implements Ability
@@ -41,7 +44,9 @@ final class MenuSetItemsAbility implements Ability
public function description(): string
{
return 'Setzt die Einträge eines Menüs. Entweder items = vollständiger Zielbaum oder operations = Liste aus '
return 'Setzt die Einträge eines Menüs. menu_rev aus lit/menu-get ist Pflicht, damit parallele Änderungen '
. 'nicht überschrieben werden; die Antwort enthält die neue menu_rev. Entweder items = vollständiger '
. 'Zielbaum oder operations = Liste aus '
. '{op: add, item, parent_id?, position?}, {op: move, id, parent_id?, position?}, {op: remove, id} '
. '(Kinder eines entfernten Eintrags rücken an seine Stelle; position 0-basiert, ohne = ans Ende). '
. 'Der Baum aus lit/menu-get kann bearbeitet unverändert zurückgegeben werden: bestehende Einträge '
@@ -67,6 +72,10 @@ final class MenuSetItemsAbility implements Ability
'type' => 'object',
'properties' => [
'menu_id' => ['type' => 'integer', 'minimum' => 1],
'menu_rev' => [
'type' => 'string',
'description' => 'menu_rev aus lit/menu-get (bzw. aus der letzten Antwort dieses Tools).',
],
'items' => [
'type' => 'array',
'items' => ['type' => 'object'],
@@ -98,7 +107,7 @@ final class MenuSetItemsAbility implements Ability
'description' => 'Nur nötig, wenn Einträge entfernt werden.',
],
],
'required' => ['menu_id'],
'required' => ['menu_id', 'menu_rev'],
'additionalProperties' => false,
];
}
@@ -107,7 +116,10 @@ final class MenuSetItemsAbility implements Ability
{
$tree = ['type' => 'array', 'items' => MenuTree::nodeSchema()];
return ToolResult::schema(['items' => $tree, 'previous_items' => $tree], ['items', 'previous_items']);
return ToolResult::schema(
['items' => $tree, 'previous_items' => $tree, 'menu_rev' => ['type' => ['string', 'null']]],
['items', 'previous_items', 'menu_rev']
);
}
public function annotations(): array
@@ -143,6 +155,13 @@ final class MenuSetItemsAbility implements Ability
}
$current = $this->currentItems($menuId);
if (($input['menu_rev'] ?? null) !== Rev::ofMenu(array_values($current))) {
return Errors::revMismatch(
'Das Menü wurde seit dem letzten Lesen geändert; nichts wurde geschrieben.',
'Mit lit/menu-get neu lesen und die Änderung auf dem aktuellen Stand (neue menu_rev) wiederholen.'
);
}
$previous = MenuTree::build(array_values($current));
$tree = array_key_exists('items', $input)
@@ -201,7 +220,7 @@ final class MenuSetItemsAbility implements Ability
$warnings
) : null;
$after = FollowUp::run(
fn () => MenuTree::build(array_values($this->currentItems($menuId))),
fn () => array_values($this->currentItems($menuId)),
$this->name() . ' re-read',
'Das Menü ist gespeichert, der neue Stand konnte aber nicht gelesen werden; mit lit/menu-get abrufen.',
$warnings
@@ -215,8 +234,9 @@ final class MenuSetItemsAbility implements Ability
return $result
->warnings($warnings)
->logId(is_int($logId) ? $logId : null)
->with('items', is_array($after) ? $after : [])
->with('items', is_array($after) ? MenuTree::build($after) : [])
->with('previous_items', $previous)
->with('menu_rev', is_array($after) ? Rev::ofMenu($after) : null)
->toArray();
}
+18 -6
View File
@@ -16,6 +16,11 @@ use WP_Post;
*/
final class PostGuard
{
private const ZERO_DATE = '0000-00-00 00:00:00';
/** wp_insert_post() publishes a "future" post on save when its date is this close (MINUTE_IN_SECONDS). */
public const PUBLISH_WINDOW = 60;
/**
* Loads an entry the current user may edit. Trashed entries are refused (every write
* on them would be surprising: publishing, scheduling or updating a trashed entry);
@@ -56,19 +61,26 @@ final class PostGuard
}
/**
* A scheduled entry whose publication time has passed (WordPress' cron missed it).
* wp_update_post() publishes such an entry on any save, so writes must not touch it.
* A scheduled entry whose publication time has passed (WordPress' cron missed it) or is
* less than a minute away: wp_insert_post() turns "future" into "publish" on any save when
* the date is within the next MINUTE_IN_SECONDS, so writes must not touch such an entry.
* A zero post_date_gmt (never set) falls back to the local post_date, like core does.
*/
public static function missedSchedule(WP_Post $post): bool
{
$gmt = (string) $post->post_date_gmt;
if ($post->post_status !== 'future' || $gmt === '' || $gmt === '0000-00-00 00:00:00') {
if ($post->post_status !== 'future') {
return false;
}
$time = strtotime($gmt . ' UTC');
$gmt = (string) $post->post_date_gmt;
if ($gmt === '' || $gmt === self::ZERO_DATE) {
$local = (string) $post->post_date;
$gmt = $local === '' || $local === self::ZERO_DATE ? '' : (string) get_gmt_from_date($local);
}
return $time !== false && $time <= time();
$time = $gmt === '' ? false : strtotime($gmt . ' UTC');
return $time !== false && $time <= time() + self::PUBLISH_WINDOW;
}
/**
@@ -120,7 +120,12 @@ final class RevisionRestoreAbility implements Ability
$backupId = RevisionPoint::capture($postId);
$restored = wp_restore_post_revision((int) $revision->ID);
if (! $restored) {
return Errors::writeFailed('WordPress konnte die Revision nicht wiederherstellen.');
return Errors::writeFailed(
'WordPress konnte die Revision nicht wiederherstellen.',
[],
null,
$backupId === null ? null : Errors::notSavedKeeping(sprintf('Revision %d', $backupId))
);
}
// The restore is saved – failures from here on are logged and reported as warnings only.
@@ -306,7 +306,8 @@ final class PostReplaceWithCopyAbility implements Ability
$detail,
null,
null,
$details
$details,
rolledBackState: Errors::notSavedKeeping(sprintf('Sicherung %d im Papierkorb', $backupId))
);
}
@@ -43,8 +43,8 @@ final class PostScheduleAbility implements Ability
public function description(): string
{
return 'Plant die Veröffentlichung eines Eintrags zu einem Zeitpunkt in der Zukunft (Ortszeit der '
. 'Website). Ein bereits veröffentlichter Eintrag ist bis dahin offline. Nur auf ausdrücklichen '
. 'Wunsch des Nutzers verwenden.';
. 'Website). Ein bereits veröffentlichter Eintrag ist bis dahin offline; ein privater Eintrag wird '
. 'zum Zeitpunkt öffentlich. Nur auf ausdrücklichen Wunsch des Nutzers verwenden.';
}
public function inputSchema(): array
@@ -99,10 +99,11 @@ final class PostScheduleAbility implements Ability
return Errors::invalidInput('Ungültiges Datum.', ['date' => 'Format JJJJ-MM-TT HH:MM erwartet']);
}
if ($date->getTimestamp() <= time()) {
// Within PUBLISH_WINDOW WordPress would publish at once instead of scheduling.
if ($date->getTimestamp() <= time() + PostGuard::PUBLISH_WINDOW) {
return Errors::invalidInput(
'Der Zeitpunkt muss in der Zukunft liegen.',
['date' => 'liegt nicht in der Zukunft'],
'Der Zeitpunkt muss mindestens eine Minute in der Zukunft liegen.',
['date' => 'liegt nicht (mindestens eine Minute) in der Zukunft'],
'Zum sofortigen Veröffentlichen lit/post-publish (direkt: lit-post-publish) verwenden.'
);
}
@@ -134,7 +135,15 @@ final class PostScheduleAbility implements Ability
}
// The status change is saved – failures from here on are logged and reported as warnings only.
$change = (new PostChangeResult($this->name(), $this->log, $postId))->afterSave($input, 'Planen');
$warnings = $post->post_status === 'private'
? [sprintf(
'Der Eintrag war privat und wird am %s ÖFFENTLICH veröffentlicht; soll er privat bleiben, die Planung '
. 'in WordPress zurücknehmen.',
$raw
)]
: [];
$change = (new PostChangeResult($this->name(), $this->log, $postId, 'die Änderung', $warnings))
->afterSave($input, 'Planen');
$title = (string) $post->post_title;
$summary = sprintf('"%s" geplant für %s', $title, $raw)
. ($post->post_status === 'publish' ? ' (war veröffentlicht und ist bis dahin offline)' : '');
@@ -16,7 +16,9 @@ use WP_Error;
use WP_Post;
/**
* lit/post-trash: moves an entry to the trash – never a permanent delete. When the
* lit/post-trash: moves an entry to the trash – never a permanent delete. Trashing the
* static front page, the posts page or an entry linked in a menu is allowed but named in
* the confirmation question and as a warning in the result. When the
* trash itself is disabled (EMPTY_TRASH_DAYS = 0), wp_trash_post() would delete the
* entry permanently (wp-includes/post.php: `if ( ! EMPTY_TRASH_DAYS ) return
* wp_delete_post( $post_id, true );`), so this tool refuses instead of calling it.
@@ -48,7 +50,8 @@ final class PostTrashAbility implements Ability
public function description(): string
{
return 'Legt einen Eintrag in den Papierkorb (nie endgültig löschen; wiederherstellbar in WordPress). '
. 'Erst nach Rückfrage beim Nutzer mit confirm: true aufrufen.';
. 'Erst nach Rückfrage beim Nutzer mit confirm: true aufrufen. Ist der Eintrag Startseite, '
. 'Beitragsseite oder in Menüs verlinkt, nennen Rückfrage und warnings das.';
}
public function inputSchema(): array
@@ -96,7 +99,12 @@ final class PostTrashAbility implements Ability
$postId = (int) $post->ID;
$title = (string) $post->post_title;
if (($input['confirm'] ?? false) !== true) {
return Errors::confirmRequired(sprintf('"%s" (ID %d) in den Papierkorb legen?', $title, $postId));
$impact = $post->post_status === 'trash' ? [] : $this->impact($post);
return Errors::confirmRequired(
trim(sprintf('"%s" (ID %d) in den Papierkorb legen? %s', $title, $postId, implode(' ', $impact))),
$impact === [] ? [] : ['warnings' => $impact]
);
}
if ($post->post_status === 'trash') {
@@ -113,6 +121,7 @@ final class PostTrashAbility implements Ability
);
}
$impact = $this->impact($post);
$trashed = StatusWrite::run(
static fn () => wp_trash_post($postId),
$this->name(),
@@ -128,7 +137,7 @@ final class PostTrashAbility implements Ability
}
// The change is saved – a failure of the change log from here on is a warning only.
$change = (new PostChangeResult($this->name(), $this->log, $postId))
$change = (new PostChangeResult($this->name(), $this->log, $postId, 'die Änderung', $impact))
->log((string) $post->post_type, sprintf('"%s" in den Papierkorb gelegt', $title));
$summary = sprintf('"%s" liegt im Papierkorb und ist dort wiederherstellbar.', $title);
@@ -138,6 +147,63 @@ final class PostTrashAbility implements Ability
->toArray();
}
/**
* What visibly breaks when $post is in the trash: the static front page / posts page
* setting points to it, or menus link it (WordPress hides such menu items while the
* entry is trashed).
*
* @return list<string>
*/
private function impact(WP_Post $post): array
{
$postId = (int) $post->ID;
$title = (string) $post->post_title;
$impact = [];
if (get_option('show_on_front') === 'page') {
if ((int) get_option('page_on_front') === $postId) {
$impact[] = sprintf(
'"%s" ist als Startseite der Website eingestellt; im Papierkorb ist sie für Besucher nicht '
. 'mehr erreichbar – unter Einstellungen → Lesen eine andere Startseite wählen.',
$title
);
}
if ((int) get_option('page_for_posts') === $postId) {
$impact[] = sprintf(
'"%s" ist als Beitragsseite der Website eingestellt; im Papierkorb ist die Beitragsübersicht '
. 'nicht mehr erreichbar – unter Einstellungen → Lesen eine andere Beitragsseite wählen.',
$title
);
}
}
$menus = $this->linkingMenus($postId);
if ($menus !== []) {
$impact[] = sprintf(
'"%s" ist in %s %s verlinkt; WordPress blendet diese Menüeinträge aus, solange der Eintrag im '
. 'Papierkorb liegt.',
$title,
count($menus) === 1 ? 'dem Menü' : 'den Menüs',
implode(', ', array_map(static fn (string $name): string => '"' . $name . '"', $menus))
);
}
return $impact;
}
/** @return list<string> Names of the menus with an item linking $postId. */
private function linkingMenus(int $postId): array
{
$items = wp_get_associated_nav_menu_items($postId, 'post_type');
if (! is_array($items) || $items === []) {
return [];
}
$names = wp_get_object_terms(array_values($items), 'nav_menu', ['fields' => 'names']);
return is_array($names) ? array_values(array_unique(array_map('strval', $names))) : [];
}
/** @param array<string, mixed> $input */
private function load(array $input): WP_Post|WP_Error
{